Same letters, any order
Two words are anagrams when their letter counts match. About 7 minutes.
Same letters, different order
"Listen" and "silent" are anagrams: the same letters, each used the same number of times, just rearranged. Order doesn't matter at all. Only the counts do.
So forget about positions. Count the letters in both words and compare the counts. If every letter appears equally often in both, they're anagrams.
Walk "listen" and add 1 to each letter's box. Same length (6 and 6), so it's worth checking.
Add for one word, subtract for the other
A neat trick: use just one row of 26 boxes. Add 1 for every letter of the first word, subtract 1 for every letter of the second. If every box ends at 0, the counts matched exactly.
Check the lengths first: words of different lengths can't be anagrams, and it saves you the walk.
if len(s) != len(t):
return False
counts = [0] * 26
for a, b in zip(s, t):
counts[ord(a) - ord("a")] += 1
counts[ord(b) - ord("a")] -= 1
return all(c == 0 for c in counts)You add 1 per letter of "abb" and subtract 1 per letter of "aab". What's left in the box for b?
- A1
- B0
- C−1
Show the answer
1. abb has two b's and aab has one: 2 − 1 = 1. They aren't anagrams.
Anagram check
You get two strings of lowercase letters. Return true if one is a rearrangement of the other (same letters, same number of times), and false otherwise.
s = "listen", t = "silent" → true
0 ≤ lengths ≤ 1,000,000 · only a to z