Valid Anagram
Frequency counting
Frequency counting with a fixed-size array or HashMap.
Problem
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An anagram uses exactly the same characters with exactly the same frequencies.
Intuition
Order is irrelevant. Counts are everything.
Two strings are anagrams if and only if every character appears the same number of times in both strings. That turns the problem from "compare permutations" into "compare frequency tables."
Because LeetCode constrains the input to lowercase English letters, we do not even need a HashMap. A fixed array of length 26 is enough.
Approach
26-slot Frequency Array
O(n)O(1)Short-circuit if the lengths differ. Then count characters in s, subtract counts for t, and confirm the table ends at all zeros.
impl Solution {
pub fn is_anagram(s: String, t: String) -> bool {
if s.len() != t.len() {
return false;
}
let mut freq = [0i32; 26];
for &b in s.as_bytes() {
freq[(b - b'a') as usize] += 1;
}
for &b in t.as_bytes() {
freq[(b - b'a') as usize] -= 1;
}
freq.into_iter().all(|x| x == 0)
}
}function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) return false;
const freq = new Array<number>(26).fill(0);
for (let i = 0; i < s.length; i++) {
freq[s.charCodeAt(i) - 97]++;
freq[t.charCodeAt(i) - 97]--;
}
return freq.every((x)=> x= 0);
}Language notes:
- Rust — bytes are ideal here because the alphabet is ASCII lowercase. No Unicode overhead, no allocation.
- TypeScript — incrementing and decrementing in the same loop keeps the code tight and avoids a second pass over the arrays.
Edge cases
- Different lengths — impossible to be anagrams.
- Repeated letters — the whole point of the frequency table is to preserve multiplicity.
- Unicode variant — if the alphabet were arbitrary Unicode, switch to
HashMap<char, i32>/Map<string, number>.
Takeaway
When order does not matter but multiplicity does, count.
That idea scales from anagram checks to bucketed counting, histogram comparisons, and signature-building for grouping problems like #49 Group Anagrams.
More in Arrays & Hashing
HashMap lookup. The most fundamental pattern: trade space for time.
HashSet existence check. Think about why this is O(n) not O(n²).
The leap: using a sorted string as a HashMap KEY. Creative key design is a core skill.
Only start counting from sequence beginnings. Think before you loop.