Check if two strings are anagram of each other
EasySame letters, same counts
Problem
Return whether two strings are anagrams (same letters, same counts).
Count each letter in both words; matching tallies mean they're anagrams.
The idea
Count each character in the first string and subtract the counts of the second; if every tally lands back on zero the strings are anagrams. Counting is O(n) where sorting both would be O(n log n).
The trick
- Different lengths mean no, without counting anything.
- A 26-slot array beats a hash map for lowercase input.
- O(n) time, O(1) space for a fixed alphabet.
t
e
a
0
1
2
Step 1 of 5. Are "tea" and "eat" anagrams? Tally "tea", then cancel with "eat". Values: t, e, a.
1/5
Optimal
timeO(n)spaceO(1)
26-slot tally (or a map).
1if (s.length !== t.length) return false;2const c = {};3for (const ch of s) c[ch] = (c[ch] ?? 0) + 1;4for (const ch of t) {5 if (!c[ch]) return false;6 c[ch]--;7}8return true;Input
- array
- [t, e, a]
Memory
- left
- —
Output
- anagram
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- s = "anagram", t = "nagaram"
- Output:
- true
- Explanation:
- Both use the same letters the same number of times.
Example 2
- Input:
- s = "rat", t = "car"
- Output:
- false
- Explanation:
- Different letters, so not an anagram.
Example 3
- Input:
- s = "a", t = "a"
- Output:
- true
- Explanation:
- Identical single letters.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.