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
- Both hold three
trueaand one each ofn,g,randm.
Example 2
- Input
- a = "rat"b = "car"
- Output
falsecis 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.
More like this
All strings examples (13) →- Reverse words Split on whitespace, walk backwards, join again.
- Common prefix Start with the whole first word, shrink until everything matches.
- Run-length encoding Collapse each run of repeats into a character and a count.
- First unique char Count every character first, then find the earliest with count 1.
- Longest unique substring A sliding window that jumps forward past any repeat.
- Caesar cipher Rotate each letter through the alphabet and wrap around.