Interview Q&A / Data Structures & Algorithms

BeginnerQuick answerCoding1 min readUpdated 3 Oct 2026

How do you check whether two strings are anagrams of each other?

SHORT ANSWER

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

js
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: false

Complexity

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).

#strings#hashing

Related questions

Practise more Data Structures & Algorithms questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Data Structures & Algorithms quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.