How do you check whether two strings are anagrams of each other?
Two strings are anagrams if they have the same letters with the same counts. Count the characters of the first string, subtract using the second, and check that every count ends at zero.
Explain it simply
"listen" and "silent" use exactly the same letters, just shuffled, like two different seating plans for the same group of friends. So compare how many of each letter you have.
Sorting both strings and comparing works, but counting is faster: one pass to add counts for the first string, one pass to subtract for the second.
Example
function isAnagram(a, b) {
if (a.length !== b.length) return false;
const count = {};
for (const ch of a) count[ch] = (count[ch] || 0) + 1;
for (const ch of b) {
if (!count[ch]) return false;
count[ch]--;
}
return true;
}
console.log(isAnagram("listen", "silent")); // Output: true
console.log(isAnagram("rat", "car")); // Output: false
console.log(isAnagram("aab", "abb")); // Output: falseComplexity
Time O(n), space O(k) where k is the number of distinct characters.
What to say in the interview
"First I compare lengths. Then I build a frequency map from the first string and decrement it while reading the second; if a letter is missing or runs out, they are not anagrams. That is O(n) time and O(k) space for k distinct characters. Sorting both strings also works in O(n log n)."
Common mistakes
- Skipping the length check.
- Ignoring case or spaces when the problem says they matter (or does not).