Valid anagram

Easy TimeO(n) SpaceO(1)

Two strings are anagrams when they hold exactly the same characters in the same quantities, in any order. Given strings a and b, return true when one is an anagram of the other and false otherwise. The comparison is case-sensitive, so "a" and "A" are different characters, and the counts must match, not merely the set of characters used.

Examples

Example 1

Input
a = "anagram"b = "nagaram"
Output
true
Both hold three a and one each of n, g, r and m.

Example 2

Input
a = "rat"b = "car"
Output
false
c is in the second string and not the first, so neither can be a rearrangement of the other.

The Code

function isAnagram(a, b) {
  if (a.length !== b.length) return false;
  const counts = {};
  for (let i = 0; i < a.length; i++) {
    counts[a[i]] = (counts[a[i]] || 0) + 1;
  }
  for (let i = 0; i < b.length; i++) {
    if (!counts[b[i]]) return false;
    counts[b[i]]--;
  }
  return true;
}
isAnagram("anagram", "nagaram");
Done

The first 11 calls, of 17. This one does not fit on a page.

Step through isAnagram("anagram", "nagaram") call by call