Valid Anagram
Difficulty: Easy · Pattern: Hashing · LeetCode #242
Given two strings s and t of lowercase English letters, return true if t is a rearrangement of the letters of s (same letters with the same multiplicities), otherwise false.
Example 1
text
s = "listen", t = "silent" → trueExample 2
text
s = "apple", t = "paple" → true
s = "rat", t = "car" → falseConstraints: 1 ≤ s.length, t.length ≤ 5·10⁴
Hints
- If the lengths differ, the answer is immediately false.
- Two strings are anagrams exactly when every letter appears the same number of times in both.
- With only 26 letters, an array of 26 counters works as a tiny hash map.
Approach
Count each letter in s (+1) and in t (−1) using a 26-slot array. The strings are anagrams iff every counter ends at zero. Checking the lengths first lets us reject quickly.
Sorting both strings and comparing also works (O(n log n)). For full Unicode input, use a hash map instead of a fixed array.
Complexity
Time: O(n). Space: O(1), since the alphabet is fixed at 26.
Python solution
def isAnagram(s, t):
if len(s) != len(t):
return False
counts = [0] * 26
for a, b in zip(s, t):
counts[ord(a) - 97] += 1
counts[ord(b) - 97] -= 1
return all(c == 0 for c in counts)JavaScript solution
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const counts = new Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
counts[s.charCodeAt(i) - 97]++;
counts[t.charCodeAt(i) - 97]--;
}
return counts.every((c) => c === 0);
}