Search⌘ K

All Anagrams

Explore how to determine if all strings in an array are anagrams of each other by implementing and analyzing two efficient JavaScript solutions. Understand character sorting and counting techniques along with their time and space complexities.

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.

Node.js
function allAnagrams(strings) {
// Your code here
}

Solution 1

Node.js
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:

  1. Turns each string into an array of characters
  2. Sorts each array of characters
  3. 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 for-loop checks to make ...