DSA Factory
Free Strings lessonsStrings · Stage 1 · Counting characters · Step 2

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.

Anagram: same letter counts, any order.
s = "listen", t = "silent" (only the letters used are shown)
eilnst
1
1
1
1
1
1

Walk "listen" and add 1 to each letter's box. Same length (6 and 6), so it's worth checking.

Move 1 of 5

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.

Every box back to 0: means the counts matched.
Different lengths: can't be anagrams.
In code
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)
Quick check

You add 1 per letter of "abb" and subtract 1 per letter of "aab". What's left in the box for b?

  1. A1
  2. B0
  3. C−1
Show the answer

1. abb has two b's and aab has one: 2 − 1 = 1. They aren't anagrams.

Your problem

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.

Example
s = "listen", t = "silent" → true

0 ≤ lengths ≤ 1,000,000 · only a to z

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve