Valid Anagram
EasySame letters, same counts
Two words are anagrams if they use the same letters the same number of times — just count and compare.
The idea
Two strings are anagrams iff every character appears the same number of times. Count letters in one, subtract with the other, and check nothing is left over.
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.