Valid Anagram — Coding Interview Walkthrough
You’re in a coding interview. The interviewer says: “Given two strings, return true if one is an anagram of the other.” You’ve seen this before. You know the answer involves character counts. But are you ready to explain the sorting trade-off? Handle the Unicode follow-up? Mention the length check before the interviewer asks? Valid Anagram is a warm-up that filters out candidates who just know the answer from candidates who can actually communicate it.
The Problem
Given two strings s and t, return true if t is an anagram of s, and false otherwise. An anagram is a word or phrase formed by rearranging the letters of another, using all the original letters exactly once.
Example 1
Input
s = "anagram", t = "nagaram"
Output
true
Example 2
Input
s = "rat", t = "car"
Output
false
Already comfortable with the solution? Practice it in a mock interview →
What Interviewers Are Actually Testing
| Skill | What Interviewers Observe |
|---|---|
| Frequency counting | Do you reach for a hash map or Counter naturally? |
| Multiple approaches | Can you compare sorting vs. counting and discuss trade-offs? |
| Edge case awareness | Do you handle unequal lengths, single characters, empty strings? |
| Unicode awareness | Do you ask about character set constraints? |
| Code clarity | Is your solution readable and concise? |
Step 1: Clarifying Questions
1. Are the strings always lowercase English letters? LeetCode guarantees this, but asking shows awareness of the Unicode follow-up. If Unicode is in scope, an array of 26 becomes a full hash map.
2. What if the lengths differ?
Unequal-length strings can’t be anagrams. Your solution should return false immediately — asking shows you’re thinking about early exits.
3. Are spaces or special characters included? Clarify whether spaces count as characters. This changes the frequency map.
4. Can the strings be empty?
Two empty strings are anagrams of each other (true). Important edge case to confirm.
Step 2: A First (Non-Optimal) Idea
Sort both strings and compare:
def isAnagram_sort(s: str, t: str) -> bool:
return sorted(s) == sorted(t)
Time: O(n log n) — dominated by sorting. Space: O(n) — for the sorted copies.
Correct and simple, but sorting is unnecessary overhead when you only need character counts.
Step 3: The Key Insight
Two strings are anagrams if and only if they have identical character frequency distributions. Count the frequency of each character in
s, subtract for each character int. If all counts return to zero, they’re anagrams. This is O(n) time and O(1) space (26-character alphabet is a fixed-size array).
Step 4: Optimal Strategy
- If
len(s) != len(t), returnFalseimmediately. - Create a frequency array of size 26 (or use
Counter). - For each character in
s, increment its count. - For each character in
t, decrement its count. - If all counts are zero, return
True. OtherwiseFalse.
Python Implementation
def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = [0] * 26 # One slot per lowercase letter
for c in s:
count[ord(c) - ord('a')] += 1
for c in t:
count[ord(c) - ord('a')] -= 1
return all(x == 0 for x in count)
Alternative using Counter (more Pythonic, same complexity):
from collections import Counter
def isAnagram(s: str, t: str) -> bool:
return Counter(s) == Counter(t)
The Counter approach is cleaner and handles Unicode naturally. The array approach is slightly faster in practice due to lower overhead.
Time & Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Single pass through each string |
| Space | O(1) | Fixed-size 26-element array (or O(k) for Unicode with k unique chars) |
Common Interview Mistakes
-
Not checking lengths first. Skipping the early
len(s) != len(t)check is a missed optimization and potential source of incorrect results. -
Using sort when frequency counting is available. Sorting is O(n log n) and is a red flag if the interviewer expects optimal solutions.
-
Forgetting the Unicode follow-up. If asked “what if the strings contain Unicode?”, the fix is switching from a 26-element array to a
Counter(dictionary). Have this answer ready. -
Using a set instead of a counter. A set only tracks presence, not frequency.
"aab"and"abb"would incorrectly returntrue. -
Not explaining the approach before coding. Anagram is fast to code — resist the urge to just type. One sentence of narration shows communication skills.
What a Strong Candidate Sounds Like
“Two strings are anagrams if they have the same character frequencies. I’ll do an early exit on unequal lengths, then count character frequencies in one pass through each string using a 26-element array. If all counts are zero after both passes, they’re anagrams. That’s O(n) time and O(1) space. If we needed to handle Unicode, I’d use a Counter dictionary instead — same logic, different data structure.”
Example Interview Dialogue
Interviewer: What if the strings could contain Unicode?
Candidate: Then the 26-element array won’t work. I’d switch to a Counter dictionary, which handles arbitrary characters. The logic is identical — count up for s, count down for t, check all values are zero. Time stays O(n), space becomes O(k) where k is the number of unique characters.
Interviewer: What’s the trade-off between sorting and counting?
Candidate: Sorting is O(n log n) and easier to write in one line. Counting is O(n) but requires more code. For small inputs the difference is negligible. In an interview I’d name both, implement the counting approach since it’s optimal, and mention sorting only as a naive alternative.
Related Problems to Practice
- Group Anagrams (LeetCode #49). Group strings that are anagrams of each other. Same frequency-counting insight, applied at scale.
- Find All Anagrams in a String (LeetCode #438). Sliding window variant — find all starting positions of anagram substrings.
- Permutation in String (LeetCode #567). Fixed-size window with frequency tracking. Direct extension.
- Valid Palindrome (LeetCode #125). Related character-level string reasoning.
- Minimum Window Substring (LeetCode #76). Advanced sliding window using frequency maps.
Practice This in a Mock Interview
Valid Anagram might feel too easy to practice — but under interview pressure, candidates still mess up the Unicode follow-up, forget the length check, or nervously reach for sort when they know counting is better. The way to make the right choice automatic is to practice explaining your reasoning out loud, not just getting the code right alone.
Start a mock interview for Valid Anagram on Intervu.
Further reading:
- How to Prepare for a Coding Interview in 2026, the complete roadmap and study plans
- Why LeetCode alone isn’t enough, and what to practice instead
- Practice any LeetCode problem as a live mock interview
- The Grind 75 Pathway, a structured study plan with AI practice links
- Browse all walkthroughs on GitHub, condensed solutions with code