Try it first — give it 10 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
s and t are anagrams if you can rearrange the letters of one to get the other, using every letter exactly once.
s = "anagram",t = "nagaram"→trues = "rat",t = "car"→false
Both strings contain only lowercase English letters.
Start with brute force
Sort both strings and compare. If they're anagrams, sorting puts the letters in the same order, so the sorted strings are equal.
That's actually a perfectly good answer: O(n log n) time and short code. But we can do it in O(n).
Building the intuition
What does "same letters, any order" really mean? It means for every letter, the count in s equals the count in t. Order is irrelevant, so we shouldn't spend time sorting.
There are only 26 lowercase letters, so a fixed array of 26 counters is all the memory we need. Map a letter to a slot with c − 'a' ('a' → 0, 'b' → 1, …, 'z' → 25).
The optimal approach
- If
len(s) != len(t), returnfalseimmediately. - Make
count = [0] * 26. - For each position
i: add 1 fors[i], subtract 1 fort[i]. - If every slot is 0, the counts matched: return
true. Otherwisefalse.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = [0] * 26 # one slot per letter a..z
for a, b in zip(s, t):
count[ord(a) - ord('a')] += 1 # letter from s
count[ord(b) - ord('a')] -= 1 # letter from t
return all(c == 0 for c in count) # anagrams cancel out exactlyclass Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
int count[26] = {0}; // one slot per letter a..z
for (size_t i = 0; i < s.size(); i++) {
count[s[i] - 'a']++; // letter from s
count[t[i] - 'a']--; // letter from t
}
for (int c : count) {
if (c != 0) return false; // some letter didn't cancel out
}
return true;
}
};class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] count = new int[26]; // one slot per letter a..z
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++; // letter from s
count[t.charAt(i) - 'a']--; // letter from t
}
for (int c : count) {
if (c != 0) return false; // some letter didn't cancel out
}
return true;
}
}/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function (s, t) {
if (s.length !== t.length) return false;
const count = new Array(26).fill(0); // one slot per letter a..z
const A = "a".charCodeAt(0);
for (let i = 0; i < s.length; i++) {
count[s.charCodeAt(i) - A]++; // letter from s
count[t.charCodeAt(i) - A]--; // letter from t
}
return count.every((c) => c === 0); // anagrams cancel out exactly
};Dry run
s = "rat", t = "car" (only non-zero counts shown)
| i | s[i] | t[i] | counts after |
|---|---|---|---|
| 0 | r | c | r: +1, c: −1 |
| 1 | a | a | r: +1, c: −1 (a cancels out) |
| 2 | t | r | t: +1, c: −1 (r cancels out) |
t and c are non-zero, so the answer is false.
Complexity
- Time: O(n). One pass over both strings, then a fixed 26-slot check.
- Space: O(1). The counter is always 26 integers, no matter how long the strings are.
Edge cases and traps
- Different lengths. Early return saves work and avoids index errors in the shared loop.
- Same letters, different counts.
"aab"vs"abb"— counting catches it, a set comparison would not. - Unicode. The 26-slot trick only works for
a–z. For any characters, use a hash map instead.
Say it in the interview
"Anagrams have identical character counts. Sorting both and comparing works in O(n log n). Better: since the input is lowercase letters, I keep a 26-slot counter, increment for s and decrement for t. If all counts end at zero they're anagrams. O(n) time, O(1) space. For Unicode I'd swap the array for a hash map."
Follow-ups interviewers ask
- "What if the strings contain Unicode?" Use a hash map from character to count.
- "Group many strings into anagram families?" That's the next problem, Group Anagrams.
- "Is any substring of s2 an anagram of s1?" A sliding window of counts — Permutation in String in the Sliding Window stage.
Practise the same idea
This is Day 11 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free