All Anagrams
Learn how to determine if multiple strings are all anagrams of each other. While it seems as if this would require a fairly poor time and space complexity, we can come up with clever solutions that make this problem tractable.
We'll cover the following...
All Anagrams
Instructions
Write a function that takes in an array of strings. Return true if all strings are anagrams of one another and false if even a single string is not an anagram of the others.
Input: Array of Strings
Output: Boolean
Examples
allAnagrams(['abcd', 'bdac', 'cabd']); // true
allAnagrams(['abcd', 'bdXc', 'cabd']); // false
Hints
- Think about what it means for two strings to be anagrams. They should all have the same characters present in the same number, perhaps in a different order.
- It would make sense to express the time complexity in terms of two variables.
Press + to interact
function allAnagrams(strings) {// Your code here}
Solution 1
Press + to interact
function allAnagrams(strings) {const sortedStrings = strings.map(str => str.split('').sort().join(''));for(let i = 1; i < strings.length; i++) {if(sortedStrings[i] !== sortedStrings[0]) {return false;}}return true;}
How it Works
Line 2 above performs several functions:
- Turns each string into an array of characters
- Sorts each array of characters
- Joins the character array back into a sorted string
If all original strings are anagrams, they should all be exactly the same string in our new array.
The ...