How to Explain Valid Anagram in a Coding Interview (Step-by-Step)

How to Explain Valid Anagram in a Coding Interview (Step-by-Step)

Valid Anagram looks deceptively simple — and it is — but interviews use it to test whether you can articulate why your approach works, not just that it works. Many candidates jump to sorting without realizing there’s a cleaner O(n) solution.

In this post, you’ll learn exactly how to walk an interviewer through the Valid Anagram problem: what to say, in what order, and which details to proactively highlight so you come across as confident and experienced.


Problem Statement

LeetCode 242 Easy

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An anagram is a word formed by rearranging the letters of another word using all original letters exactly once.

Examples

Example 1
Input: s = “anagram”, t = “nagaram”
Output: true
Example 2
Input: s = “rat”, t = “car”
Output: false

Constraints

  • 1 <= s.length, t.length <= 5 * 10⁴
  • s and t consist of lowercase English letters only

What Is the Problem?

Before writing a single line of code, restate the problem in your own words:

“I need to check whether two strings contain exactly the same characters with exactly the same frequencies. The order doesn’t matter — only the character counts.”

Restating it as a frequency comparison problem immediately hints at the optimal approach.


Step 1: Start With the Brute Force (Then Dismiss It)

Always acknowledge the naive approach first:

“The simplest approach is to sort both strings and check if they’re equal. If they’re anagrams, sorting will produce the same string. That’s clean, readable, and correct — but O(n log n) due to sorting.”

Then pivot to optimal:

“We can do better with a HashMap. Count the frequency of each character in both strings and compare the maps. That’s O(n) time and O(1) space — since we’re dealing with a fixed 26-letter alphabet.”
⚠️ Sort Both Strings

Sort s and t, compare if equal

Time: O(n log n)   Space: O(1)

✅ HashMap Count (Optimal)

Count char frequencies, compare maps

Time: O(n)   Space: O(1)*

* O(1) space because the alphabet is fixed at 26 characters — the map never grows beyond 26 keys regardless of input size.


Step 2: Explain the Algorithm in Plain English

“First I check if the lengths are equal — if not, they can’t be anagrams. Then I count the frequency of each character in s using a HashMap, and decrement for each character in t. At the end, if all counts are zero, the strings are anagrams. If any count is non-zero, they’re not.”

Alternatively, using Python’s Counter:

“In Python I can use Counter from the collections module to count both strings and directly compare the two Counter objects.”

Step 3: Talk Through the Code

Approach 1 — Manual HashMap (recommended in interviews)

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):   # Quick early exit — lengths must match
            return False

        count = {}  # HashMap to track character frequency difference

        for c in s:
            count[c] = count.get(c, 0) + 1  # Increment for chars in s

        for c in t:
            count[c] = count.get(c, 0) - 1  # Decrement for chars in t
            if count[c] < 0:                 # More of this char in t than s
                return False

        return True  # All frequencies balanced out

Approach 2 — Python Counter (concise, good to mention)

from collections import Counter

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return Counter(s) == Counter(t)  # Direct frequency comparison

Mention both — the manual approach shows you understand the mechanics, the Counter approach shows you know the standard library.


Visual Walkthrough

Trace through s = "anagram", t = "nagaram" to show how counts balance to zero:

Character frequency after processing s="anagram", t="nagaram"
CharCount after sCount after tFinal
a+3-30 ✓
n+1-10 ✓
g+1-10 ✓
r+1-10 ✓
m+1-10 ✓

All counts zero → true. This visual is great to draw on a whiteboard during the interview.


Step 4: Highlight Edge Cases

1 Different lengths
"If len(s) != len(t) we return false immediately. Two strings of different lengths can never be anagrams — this early check saves unnecessary computation."
2 Same characters, different counts
"s = "aab", t = "abb" — same length, same characters, but different frequencies. The HashMap correctly returns false because a's count will be +1 and b's will be -1."
3 Single character strings
"s = "a", t = "a"true. s = "a", t = "b"false. Both handled correctly by the general logic."

Step 5: State Time and Space Complexity

DimensionComplexityReason
Time O(n) Two passes through the strings — both O(n)
Space O(1) Map has at most 26 keys — fixed size regardless of input

Follow-up: What If the Input Contains Unicode?

Interviewers commonly ask this as a follow-up. Be ready:

"The constraint says lowercase English letters only, so our 26-character bound holds. But if the input could contain Unicode — thousands of possible characters — the space complexity becomes O(k) where k is the size of the character set. The HashMap approach still works correctly without any code changes. The sorting approach also still works. So our solution is already Unicode-safe."

This is a great answer because it shows you read the constraints carefully and can reason beyond them.


Interview Checklist for Valid Anagram

  • Restate — "check if both strings have the same character frequencies"
  • Mention sorting approach O(n log n) first, then HashMap O(n)
  • Explain the increment/decrement frequency logic in plain English
  • Mention the early length check as an optimization
  • Call out same-chars-different-counts edge case
  • Explain why space is O(1) — fixed 26-character alphabet
  • State O(n) time and O(1) space
  • Answer the Unicode follow-up proactively
  • Mention Python Counter as a concise alternative
  • Ask before coding, don't just dive in

If you can solve Valid Anagram cleanly, try these next:

💡 Practicing your explanations out loud is just as important as writing correct code. The best candidates aren't the ones who solve it fastest — they're the ones who make the interviewer feel like they're thinking alongside them.
Scroll to Top