String AnagramLoading saved progress…

String Anagram

An anagram is a string formed by rearranging the characters of another — "listen" and "silent" use the same six letters in a different order. Implement stringAnagram(a, b) to return true when a and b contain the same characters with the same counts, and false otherwise. The comparison is case-sensitive and whitespace-significant"Listen" and "silent" are not anagrams, and neither are "a b" and "ab".

Signature

function stringAnagram(a, b) {
  // returns true if a and b are anagrams of each other,
  // false otherwise. Case-sensitive, whitespace-significant.
}

Examples

stringAnagram('listen', 'silent');
// true

stringAnagram('hello', 'world');
// false  (different characters)

stringAnagram('abc', 'abcd');
// false  (different lengths)
// Case-sensitive: 'L' and 'l' count as different characters.
stringAnagram('Listen', 'silent');
// false

// Two empty strings are trivially anagrams (no characters to mismatch).
stringAnagram('', '');
// true

// Repeated characters must match in count, not just in presence.
stringAnagram('aab', 'abb');
// false  ('aab' has two a's; 'abb' has only one)

Notes

  • Lengths must match. If a.length !== b.length the answer is immediately false — no need to look at characters.
  • Counts matter, not just presence. "aab" and "abb" share the same character set but different character counts; they are not anagrams.
  • Case-sensitive. 'A' !== 'a' for this question. If you want case-insensitive behavior, the caller should lowercase both inputs before calling.
  • Whitespace counts. Spaces, tabs, and newlines are characters like any other. "a b" and "ab" have different lengths, so they are not anagrams.
  • Don't mutate the inputs. Strings are primitives in JavaScript so this is automatic, but if you sort the characters, sort a copy ([...str]) — don't try to mutate the string itself.
Loading editor…