Home
DSA Patterns
Hash Map
Valid Anagram
Valid Anagram (LeetCode 242)
Valid Anagram (LeetCode 242): decide whether two strings are anagrams by counting letters in a hash map.
Problem Understanding
Valid Anagram: given two strings s and t, return true if t is an anagram of s: the same letters, each used the same number of times, in any order.
Examples: s = "anagram", t = "nagaram" is true. s = "rat", t = "car" is false.
Attempt 1: Sort Both Strings
Sort the letters of both strings and compare: anagrams sort to the same string. It is correct and short, but sorting costs O(n log n) time. The question underneath: does every letter appear the same number of times in both?, can be answered by counting, without ordering anything.
The Intuition: Count, Then Spend
A hash map from letter to count turns the question into bookkeeping:
- If the lengths differ, return
falseimmediately. - Walk
sand add one to each letter's count. - Walk
tand spend one count per letter. If a letter's count is already0,thas more of that letter thans: returnfalse.
If t finishes without running out of anything, the strings are anagrams. The length check is what makes that last step safe: equal lengths and nothing overspent means every count ended at exactly 0.
Valid Anagram Visualization
s = "anagram", t = "nagaram"
LENGTHS MATCH
s
0
1
2
3
4
5
6
t
0
1
2
3
4
5
6
Answer
:
count (letter:count)
Empty
Both strings have 7 letters. Start an empty count
Next
s[0] = 'a': count['a'] is now 1
s
t
Both strings are drawn as rows. The first pass walks s while the count map beside the figure grows; the second walks t while the counts fall and matched letters grey out. A letter of t that finds its count at 0 ends the run.
Valid Anagram Dry Run
Input: s = "rat", t = "car"
| Step | Letter | Action | count after |
|---|---|---|---|
| 1 | - | lengths 3 = 3, continue | {} |
| 2 | s[0] = 'r' |
count | {r: 1} |
| 3 | s[1] = 'a' |
count | {r: 1, a: 1} |
| 4 | s[2] = 't' |
count | {r: 1, a: 1, t: 1} |
| 5 | t[0] = 'c' |
count['c'] is 0 |
return false |
t asks for a 'c' that s never had.
Valid Anagram LeetCode Solution
Letter counts in a hash map; in C, an array of 26 counts plays the same role.
Valid Anagram Code
1var isAnagram = function(s, t) {2 if (s.length !== t.length) {3 return false;4 }5 const count = new Map();6 for (const ch of s) {7 count.set(ch, (count.get(ch) || 0) + 1);8 }9 for (const ch of t) {10 if (!count.get(ch)) {11 return false;12 }13 count.set(ch, count.get(ch) - 1);14 }15 return true;16};
Valid Anagram in Python, Java, C++, TypeScript and C
Valid Anagram in Python
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = {}
for ch in s:
count[ch] = count.get(ch, 0) + 1
for ch in t:
if count.get(ch, 0) == 0:
return False
count[ch] -= 1
return TrueValid Anagram in Java
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
Map<Character, Integer> count = new HashMap<>();
for (char ch : s.toCharArray()) {
count.merge(ch, 1, Integer::sum);
}
for (char ch : t.toCharArray()) {
if (count.getOrDefault(ch, 0) == 0) {
return false;
}
count.merge(ch, -1, Integer::sum);
}
return true;
}
}Valid Anagram in C++
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) {
return false;
}
unordered_map<char, int> count;
for (char ch : s) {
count[ch]++;
}
for (char ch : t) {
if (count[ch] == 0) {
return false;
}
count[ch]--;
}
return true;
}
};Valid Anagram in TypeScript
function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) {
return false;
}
const count = new Map<string, number>();
for (const ch of s) {
count.set(ch, (count.get(ch) ?? 0) + 1);
}
for (const ch of t) {
if (!count.get(ch)) {
return false;
}
count.set(ch, count.get(ch)! - 1);
}
return true;
}Valid Anagram in C
bool isAnagram(char* s, char* t) {
if (strlen(s) != strlen(t)) {
return false;
}
int count[26] = {0}; // s and t are lowercase English letters
for (char *p = s; *p; p++) {
count[*p - 'a']++;
}
for (char *p = t; *p; p++) {
if (count[*p - 'a'] == 0) {
return false;
}
count[*p - 'a']--;
}
return true;
}Edge Cases & Common Mistakes
- Different lengths: return
falsebefore counting anything. - Same letters, different amounts (
"aab","abb"): the second'b'oftfinds its count at0. - Skipping the length check:
"ab"and"abc"would then need a final scan for leftover counts: the check removes that scan. - Unicode input: the hash map version works for any characters; the 26-slot array only for lowercase English letters.
Summary
Counting with a hash map replaces sorting: build the counts from one string, spend them on the other, and stop the moment something runs out. The same frequency map, keyed differently, is the heart of Group Anagrams.
More practice: DSA interview questions with answers · patterns cheat sheet
