242. Valid Anagram
At a Glance
- Topic: arrays-hashing
- Pattern: Hash Map Counting
- Difficulty: Easy
- Companies: Amazon, Google, Meta, Bloomberg, Microsoft
- Frequency: High
- LeetCode: 242
Problem (one-liner)
Given two strings first and second, return true if second is an anagram of first (same multiset of characters), else false. Typically lowercase English letters.
Recognition Cues
- "Anagram", "permutation of letters", "same characters same counts"
- Length mismatch immediately implies false
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force — sort both strings and compare —
O(n log n)time /O(1)extra if sorting in place allowed on copies. - Better — two frequency maps merge —
O(n)time /O(1)space (alphabet size fixed). - Optimal — single array of 26 counts: increment for
first, decrement forsecond—O(n)time /O(1)space.
Optimal Solution
Go
package main
func isAnagram(first string, second string) bool {
if len(first) != len(second) {
return false
}
counts := [26]int{}
for index := range first {
counts[first[index]-'a']++
counts[second[index]-'a']--
}
for _, value := range counts {
if value != 0 {
return false
}
}
return true
}JavaScript
function isAnagram(first, second) {
if (first.length !== second.length) {
return false;
}
const counts = new Array(26).fill(0);
for (let index = 0; index < first.length; index++) {
counts[first.charCodeAt(index) - 97]++;
counts[second.charCodeAt(index) - 97]--;
}
return counts.every((value) => value === 0);
}Walkthrough
Input: first = "anagram", second = "nagaram"
| index | first[index] | second[index] | counts delta (conceptual) |
|---|---|---|---|
| 0 | a | n | +a, -n |
| 1 | n | a | balance toward zero per letter |
| 2 | a | g | … |
| 3 | g | a | … |
| (end) | — | — | all 26 counters zero → true |
After full pass, multiset difference must be all zeros.
Edge Cases
- Empty strings → true.
- Same string → true.
- Different lengths → false without full scan.
Pitfalls
- Using sort and forgetting
O(n log n)cost when linear suffices. - Unicode / extended alphabet — problem scope may be ASCII only.
Similar Problems
- 049. Group Anagrams — same signature bucketing.
- 217. Contains Duplicate — multiset / membership on values.
- 001. Two Sum — complementary use of hash structures.
Variants
- Unicode: use rune map instead of size-26 array.
- Count steps to transform one string into another (edit distance is different problem).
Mind-Map Tags
#hashmap #strings #anagram #frequency #counting
Last updated on
Spotted something unclear or wrong on this page?