Why they ask this: Checks counting with a hash map and comparing frequency, a pattern used in many string problems.
Problem
Given two lowercase strings a and b, return true if b is an anagram of a (it uses exactly the same letters the same number of times), otherwise false.
Example 1
text
Input: a = "listen", b = "silent"
Output: trueExample 2
text
Input: a = "rat", b = "car"
Output: falseHints
Approach
- If the lengths differ, return
false. - Count how many times each character appears in
ausing a map. - Walk through
band decrement the count of each character. If a character is missing or its count is already zero, returnfalse. - Because the lengths are equal and no count went below zero, every count is zero, so return
true.
Sorting both strings and comparing them also works, but costs O(n log n).
Solution
js
function isAnagram(a, b) {
if (a.length !== b.length) return false;
const counts = new Map();
for (const ch of a) {
counts.set(ch, (counts.get(ch) ?? 0) + 1);
}
for (const ch of b) {
const remaining = counts.get(ch);
if (!remaining) return false; // missing or already used up
counts.set(ch, remaining - 1);
}
return true;
}
console.log(isAnagram('listen', 'silent')); // true
console.log(isAnagram('rat', 'car')); // false Time
O(n) Space O(k), k = number of distinct charactersCan you explain this in your own words?