Approach Summary
Count character frequencies in s, decrement for t. If all counts are 0, they are anagrams.
Full Solution & Approach
Two strings are anagrams if they contain the same characters with the same frequencies. The shortest path is to sort both and compare — O(n log n) and trivial but not optimal. Better: count character frequencies with a hash map in one pass over s, then decrement over t. If t ever references a character not in the map, or a count already at 0, it has a character s does not — return false. At the end every count must have been decremented back to 0, so the map must be empty. This is O(n) time and O(1) space in practice because the alphabet is bounded (26 lowercase letters or 128 ASCII). The frequency-counter pattern is the workhorse behind almost every anagram and permutation-in-string problem on LeetCode, so it is worth internalizing over the sort shortcut.
Two linear passes with O(1) hash operations per character — O(n) time. The map holds at most the alphabet size — bounded constant space.
Solution Code
Solution
from collections import Counter
def is_anagram(s: str, t: str) -> bool:
return Counter(s) == Counter(t)function isAnagram(s, t) {
if (s.length !== t.length) return false;
const counts = new Map();
for (const ch of s) counts.set(ch, (counts.get(ch) || 0) + 1);
for (const ch of t) {
if (!counts.has(ch)) return false;
counts.set(ch, counts.get(ch) - 1);
if (counts.get(ch) === 0) counts.delete(ch);
}
return counts.size === 0;
}public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++;
count[t.charAt(i) - 'a']--;
}
for (int c : count) if (c != 0) return false;
return true;
}bool isAnagram(const string& s, const string& t) {
if (s.size() != t.size()) return false;
int count[26] = {};
for (int i = 0; i < (int)s.size(); i++) {
count[s[i] - 'a']++;
count[t[i] - 'a']--;
}
for (int c : count) if (c != 0) return false;
return true;
} Edge Cases to Watch
- Different lengths — immediately false
- Empty strings — true
- Unicode characters — the map keys on any character, so any alphabet works
- Repeated characters — the count-based check is exact
How to Recognize This Pattern
- Check if two strings contain same characters
Complexity Analysis
Time Complexity
O(n)
Space Complexity
O(1)