📖 5 min read
Last updated on

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.

(LeetCode #242)

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

SkillWhat Interviewers Observe
Frequency countingDo you reach for a hash map or Counter naturally?
Multiple approachesCan you compare sorting vs. counting and discuss trade-offs?
Edge case awarenessDo you handle unequal lengths, single characters, empty strings?
Unicode awarenessDo you ask about character set constraints?
Code clarityIs 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 in t. 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

  1. If len(s) != len(t), return False immediately.
  2. Create a frequency array of size 26 (or use Counter).
  3. For each character in s, increment its count.
  4. For each character in t, decrement its count.
  5. If all counts are zero, return True. Otherwise False.

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

AspectComplexityExplanation
TimeO(n)Single pass through each string
SpaceO(1)Fixed-size 26-element array (or O(k) for Unicode with k unique chars)

Common Interview Mistakes

  1. Not checking lengths first. Skipping the early len(s) != len(t) check is a missed optimization and potential source of incorrect results.

  2. Using sort when frequency counting is available. Sorting is O(n log n) and is a red flag if the interviewer expects optimal solutions.

  3. 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.

  4. Using a set instead of a counter. A set only tracks presence, not frequency. "aab" and "abb" would incorrectly return true.

  5. 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.



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:

Practice Like It's the Real Interview

Get instant feedback on your approach, communication, and code — powered by AI.

Start a Mock Interview →