Approach Summary
Count character frequencies in s, decrement for t. If all counts are 0, they are anagrams.
Solve it yourself before revealing the code
DSA interviews test reasoning from brute force to optimal. Think through the constraints first.
Solution Progression (Brute Force → Most Optimized)
Understand the architectural evolution from naive baseline to optimal complexity.
| Approach | Time | Space | Core Strategy / Trade-off |
|---|---|---|---|
| 1 Approach 1: Sorting | O(n log n) | O(1) or O(n) depending on language string immutability | Sort both strings alphabetically and test for equality in O(n log n). |
| 2 Approach 2: Character Frequency Array / Map (Optimal) | O(n) | O(1) [at most 26 entries] | Count character occurrences using a 26-element array or hash map in linear time. |
Approach 1: Sorting
If two strings are anagrams, their sorted sequences of characters must be identical. Sort both strings and compare them character by character. If equal, return true; otherwise return false.
Approach 1: Sorting Implementation
Approach 1: Sorting
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
char[] sArr = s.toCharArray();
char[] tArr = t.toCharArray();
Arrays.sort(sArr);
Arrays.sort(tArr);
return Arrays.equals(sArr, tArr);
}
}class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)function isAnagram(s, t) {
if (s.length !== t.length) return false;
return s.split('').sort().join('') === t.split('').sort().join('');
} Approach 2: Character Frequency Array / Map (Optimal)
Maintain a character frequency map. Increment for each character in s, and decrement for each character in t. If any character in t is missing or its count falls below zero, return false immediately. If the map is empty or all counts are zero at the end, return true.
Approach 2: Character Frequency Array / Map (Optimal) Implementation
Approach 2: Character Frequency Array / Map (Optimal)
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
}
for (int i = 0; i < t.length(); i++) {
if (!map.containsKey(t.charAt(i))) return false;
map.put(t.charAt(i), map.get(t.charAt(i)) - 1);
if (map.get(t.charAt(i)) == 0) map.remove(t.charAt(i));
}
return map.isEmpty();
}
}class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
unordered_map<char, int> map;
for (char c : s) map[c]++;
for (char c : t) {
if (map.find(c) == map.end()) return false;
map[c]--;
if (map[c] == 0) map.erase(c);
}
return map.empty();
}
};class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
freq = {}
for c in s:
freq[c] = freq.get(c, 0) + 1
for c in t:
if c not in freq:
return False
freq[c] -= 1
if freq[c] == 0:
del freq[c]
return len(freq) == 0function isAnagram(s, t) {
if (s.length !== t.length) return false;
const map = new Map();
for (const c of s) map.set(c, (map.get(c) || 0) + 1);
for (const c of t) {
if (!map.has(c)) return false;
map.set(c, map.get(c) - 1);
if (map.get(c) === 0) map.delete(c);
}
return map.size === 0;
} Edge Cases to Watch
- Different lengths (e.g. s = "a", t = "ab"; returns false immediately)
- Identical strings (e.g. s = "anagram", t = "anagram"; returns true)
- Single character matching / non-matching
- Non-English / Unicode characters (handled via HashMap instead of fixed 26 array)
Master the Hash Map / Set Pattern
Study the core invariant, step-by-step decision framework, and common interview traps for the Hash Map / Set pattern.
How to Recognize This Pattern
- Check if two strings contain same characters
Complexity Analysis
Time Complexity
O(n)
Space Complexity
O(1)