Difficulty: Easy · LeetCode 242
Problem
Given two strings s and t, return true if t is an anagram of s. An anagram uses the exact same characters with identical frequencies.
Examples
Input
s, t: str (lowercase English letters)
1 ≤ len ≤ 5×104
Output
boolean — true if anagram
Constraints
1 ≤ s.length, t.length ≤ 5×104s and t consist of lowercase English letters
Understanding the problem
Anagrams share identical character frequency distributions. Quick check: if lengths differ, immediately false. Then compare frequency maps — a hashmap/counter approach is O(n).
Intuition
Count character frequencies with a hashmap. Two strings are anagrams iff their frequency maps are identical. Single O(n) pass instead of O(n log n) sort.
Approach
If
len(s) != len(t)→ return False.Build frequency map for
s.For each char in
t, decrement its count.If any count goes negative → return False.
Return True.
Naive Solution — Sorting
Sort both strings. If anagrams, sorted versions are equal.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};class Solution {
public boolean isAnagram(String s, String t) {
char[] a = s.toCharArray(), b = t.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
return Arrays.equals(a, b);
}
}var isAnagram = function(s, t) {
return s.split('').sort().join('') === t.split('').sort().join('');
};Time: O(n log n) · Space: O(1)
Optimized Code — HashMap O(n)
from collections import Counter
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
int count[26] = {};
for (char c : s) count[c-'a']++;
for (char c : t) if (--count[c-'a'] < 0) return false;
return true;
}
};class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] count = new int[26];
for (char c : s.toCharArray()) count[c-'a']++;
for (char c : t.toCharArray()) if (--count[c-'a'] < 0) return false;
return true;
}
}var isAnagram = function(s, t) {
if (s.length !== t.length) return false;
const map = {};
for (const c of s) map[c] = (map[c]||0) + 1;
for (const c of t) { if (!map[c]) return false; map[c]--; }
return true;
};Time: O(n) · Space: O(1)*
Variants
Takeaway
Pattern: Character Frequency Map — "Same characters, different order" → compare frequency maps. Applies to anagram detection, permutation checking, group-by-signature problems.