← Back to libraryQuestion 158 of 468
🧩JavaScript CodingIntermediate

Check if Two Strings are Anagrams

📌 Definition:

Determine whether two strings contain the same characters with the same counts (e.g. 'listen' and 'silent').

📖 Detailed Explanation:

Two common approaches: (1) sort both and compare — O(n log n); (2) build a frequency map from the first string and decrement with the second — O(n). Normalize case/whitespace if required.

💻 Solutions:
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;
}
🔑 Key Points:
  • Early exit if lengths differ
  • Frequency-map approach is O(n) vs O(n log n) for sort
  • Decrement and check for negatives/missing
  • Normalize case/spaces if the spec requires
🌍 Real-World Example:

Anagram checks show up in fuzzy matching and in test-data generation where you verify a shuffle preserved all elements.

🎯 Scenario-Based Interview Question:

isAnagram('rat', 'car') should be false but a length-only + sum-of-char-codes check returns true for some inputs. Why is summing char codes wrong?