Jump to section
- The Valid Anagram Problem
- Start With the Simple Answer: Sort Both Strings
- The Optimal Approach: Count the Letters
- Valid Anagram Solution in Python and TypeScript
- Time and Space Complexity
- How to Talk Through Valid Anagram in an Interview
- Edge Cases and Common Follow-Ups
- Practise Valid Anagram in a Mock Coding Round
- FAQ
Valid Anagram asks whether two strings contain exactly the same characters, each the same number of times, in any order. The optimal solution counts the characters of the first string in a hash map, then subtracts the second string's characters and fails on any negative count. It runs in O(n) time and O(k) space, where k is the number of distinct characters.
The Valid Anagram Problem
You are given two strings, s and t. Return true if t is an anagram of s: it uses every character of s exactly as often, just rearranged. Otherwise return false.
Example 1
Input: s = "listen", t = "silent"
Output: true
Why: both strings contain one each of e, i, l, n, s and t.
Example 2
Input: s = "aab", t = "abb"
Output: false
Why: the same set of letters appears in both, but the counts differ: two a's against one. Checking only which letters appear is a common wrong answer.
Assumptions to confirm
- Is the input lowercase English letters only, or any Unicode text? (It changes whether a fixed array of 26 counts is enough.)
- Do spaces and capital letters count? ("Dormitory" and "dirty room" are anagrams only if you ignore both.)
- Are two empty strings anagrams? (Usually yes.)
Start With the Simple Answer: Sort Both Strings
The quickest correct answer sorts both strings and compares them. If the sorted versions are equal, the strings are anagrams. It takes O(n log n) time and, in most languages, O(n) extra space for the sorted copies.
Say this first. It is short, obviously correct and a fine fallback. Then point out what it does that you do not need: it puts every character in order, when the question only cares how many times each one appears. Counting is cheaper than ordering, which leads to the linear solution.
Ready to put this into practice?
Practice this with MockIF →Still applying for jobs? Let Auto Apply do it
The Optimal Approach: Count the Letters
Compare lengths first
Strings of different lengths can never be anagrams, so return false straight away. It is also what makes the next steps correct.
Count every character of the first string
Use a hash map from character to count. For lowercase letters only, an array of 26 integers works the same way.
Subtract the characters of the second string
For each character, decrease its count by one.
Fail fast on a negative count
A count below zero means the second string uses a character more often than the first, so the answer is false.
Return true at the end
Because the lengths match and no count went negative, every count must be exactly zero.
Valid Anagram Solution in Python and TypeScript
Both versions follow the steps above. The length check is what lets them skip a final pass to confirm every count is zero.
Python
from collections import Counter
def is_anagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
counts = Counter(s)
for ch in t:
counts[ch] -= 1
if counts[ch] < 0:
return False
return True
TypeScript
function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) return false;
const counts = new Map<string, number>();
for (const ch of s) counts.set(ch, (counts.get(ch) ?? 0) + 1);
for (const ch of t) {
const left = (counts.get(ch) ?? 0) - 1;
if (left < 0) return false;
counts.set(ch, left);
}
return true;
}
In Python, Counter(s) == Counter(t) is a valid one-line answer and worth mentioning, but write the explicit loop if the interviewer asks how it works. Many interviewers do.
Ready to put this into practice?
Practice this with MockIF →Still applying for jobs? Let Auto Apply do it
Time and Space Complexity
| Approach | Time | Space | When to use it |
|---|---|---|---|
| Sort and compare | O(n log n) | O(n) | Your first spoken answer, or very short strings |
| Hash map of counts | O(n) | O(k) distinct characters | The expected interview answer, any character set |
| Array of 26 counts | O(n) | O(1) | Lowercase English letters only |
How to Talk Through Valid Anagram in an Interview
A strong spoken answer follows the same five beats every time:
- Clarify: "Is it lowercase letters only, or any characters? Do spaces and case matter?"
- Brute force: "I could sort both strings and compare them, which is O(n log n)."
- Optimise: "I only need counts, not order, so I can count the first string in a map and subtract the second. That is one pass over each string, so O(n)."
- Code: say why the length check comes first and why a negative count means you can stop early.
- Test: run "listen" and "silent", then "aab" and "abb", then two empty strings. State O(n) time and O(k) space.
On an easy problem like this, the difference between a pass and a strong pass is usually the clarifying questions and the edge cases, not the code.
Ready to put this into practice?
Practice this with MockIF →Still applying for jobs? Let Auto Apply do it
Edge Cases and Common Follow-Ups
Different lengths
Return false immediately. Without this check, you would need a final pass to confirm every count is zero.
Same letters, different counts
"aab" and "abb" share the same set of letters. Comparing sets instead of counts is the most common bug.
Unicode input
A fixed array of 26 breaks on accented or non-Latin characters. A hash map handles any character, at the cost of a little more memory.
Case and spaces
If the interviewer says to ignore them, normalise both strings first: lower-case them and remove spaces.
Many words at once
Grouping a whole list of words into anagram families is the follow-up problem, Group Anagrams.
Practise Valid Anagram in a Mock Coding Round
Valid Anagram is often used as a warm-up in a screening round, so the interviewer is listening for how clearly you clarify and test, not just whether the code works. Rehearsing it out loud, under time pressure, is the quickest way to make that habit automatic.
MockIF runs mock coding interviews with a voice AI interviewer in a real in-browser editor, in Python and TypeScript. It runs your code against tests, asks you to explain your approach, adds follow-up questions the way a real interviewer would, and then scores your answer and gives specific feedback. Each session costs 2 credits. It is free to start with 5 credits, then monthly or 3-monthly plans, or one-off credit packs (see pricing).
Frequently Asked Questions
How do you check if two strings are anagrams?
What is the time complexity of Valid Anagram?
Can you solve Valid Anagram in O(1) space?
Is Valid Anagram an easy interview question?
Stop Preparing in Your Head. Start Practicing Out Loud.
Drop your resume, add a job description, and get a mock interview like the real thing.
Start Free Mock Interview →Still applying for jobs? Let Auto Apply do it for you.