Valid Anagram solution explained

To check whether two strings are anagrams, compare their character counts: if the lengths differ the answer is no, otherwise add one per character of the first string, subtract one per character of the second, and confirm every count ends at zero. That is O(n) time with memory bounded by the alphabet, versus O(n log n) for the equally correct sort-and-compare answer.

By Published 7 min read

The task, restated

You get two strings. Say yes if you can rearrange the letters of the first to spell the second exactly, using every letter once. Say no otherwise. Two copies of the same word count as anagrams of each other. Spaces, case and punctuation are whatever the interviewer says they are, so the first move is to ask.

Inputs made up for this walkthrough
FirstSecondAnagrams?Reason
stonenotesYesSame five letters, new order
looppoolYesTwo o's on each side
looppoloYesOrder is irrelevant, only counts matter
kettlekettlNoLengths differ, so stop at once
aababbNoSame letters, wrong counts
two empty stringsYesNothing to rearrange, nothing left over
Inputs made up for this walkthrough. Scroll sideways on a small screen.

Questions worth asking before you code: Are the strings lowercase English letters only, or any text? Should Stone match notes, which means folding case first? Do spaces count, as in dormitory versus dirty room? The common version of this problem keeps it simple, with lowercase letters and no spaces, but saying the assumption out loud costs five seconds and prevents a wrong answer.

What the interviewer is listening for

This is a short warm-up, often given early in a phone screen or paired with a harder second question. The bar is not cleverness. It is whether you can pick a data structure that matches the question, state its cost, and handle the obvious early exit when lengths differ. A candidate who mentions both the sort answer and the counting answer, and can say when each one is the better choice, usually clears this quickly.

  • Can you avoid sorting? Counting is linear. Say why: each character is visited once on each side.
  • Can you use a fixed array? With only lowercase letters, 26 integers replace the dictionary, which is faster in practice and constant in memory.
  • What about Unicode? Code points, combining accents and emoji make a single visible character span several units. Normalize first, then count.
  • Many words at once? That is a different problem, grouping anagrams, and it reuses the same signature idea as a dictionary key.

Simple first answer: sort and compare

Two strings are anagrams exactly when their sorted forms are identical, because sorting erases order and keeps counts. In Python that is one line. The cost is the sort: O(n log n) time and O(n) extra space for the sorted copies, since strings are immutable in both Python and JavaScript.

def same_letters_sorted(first, second):
    return sorted(first) == sorted(second)
Sort-based check, O(n log n). Also a handy reference to test faster versions against.

This answer is correct, and in some interviews it is enough. Offer it first, give its cost, then ask whether the interviewer wants linear time. Most do.

Linear answer: one count table

Keep a table from character to a running balance. Walk the first string and add one for each character. Walk the second and subtract one. If any balance goes negative during the second walk, the second string used a character more often than the first, so you can return no immediately. When the lengths match and nothing went negative, every balance must be zero, so the answer is yes.

The length check up front is what makes the early exit sound. Without it, ab against a would never drive a count negative and you would need a final scan of the table.

def same_letters(first, second):
    if len(first) != len(second):
        return False
    balance = {}
    for ch in first:
        balance[ch] = balance.get(ch, 0) + 1
    for ch in second:
        left = balance.get(ch, 0) - 1
        if left < 0:
            return False
        balance[ch] = left
    return True
Python: dictionary of balances, O(n) time.
function sameLettersLower(first, second) {
  if (first.length !== second.length) return false;
  const counts = new Array(26).fill(0);
  const base = "a".charCodeAt(0);
  for (let i = 0; i < first.length; i++) {
    counts[first.charCodeAt(i) - base] += 1;
    counts[second.charCodeAt(i) - base] -= 1;
  }
  return counts.every((c) => c === 0);
}
JavaScript: a 26-slot array when the input is lowercase a to z.

The JavaScript version walks both strings in the same loop and checks all slots at the end, which is a fine alternative to the early exit. It only works when every character really is a lowercase letter; on other input the index falls outside the array. If the input is wider, swap the array for a Map keyed by character.

Python also offers collections.Counter(first) == Counter(second), which is linear and short. Using it is fine in most rounds, but be ready to write the loop if the interviewer asks what the library call does underneath.

Cost of each approach

Time and extra memory, n being the string length and k the alphabet size
ApproachTimeExtra spaceNotes
Sort both, compareO(n log n)O(n)Shortest code, good opening answer
Dictionary of balancesO(n)O(k)Works for any characters
Fixed array of 26O(n)O(1)Only for a known small alphabet
Counter equality (Python)O(n)O(k)Fine to use, know what it does
Time and extra memory, n being the string length and k the alphabet size. Scroll sideways on a small screen.

Edge cases to try

  • Both strings empty: yes.
  • One empty, one not: the length check says no.
  • Equal lengths, same set of letters, different counts, like aab and abb.
  • A string compared with itself: yes.
  • Upper and lower case mixed, if the interviewer said case should not matter. Fold to one case first.
  • Text outside a to z with the 26-slot array: guard it, or switch to a dictionary.

Where people lose points

  • Comparing sets of characters. aab and abb have the same set and are not anagrams.
  • Forgetting the length check and then trusting the early exit alone.
  • Calling the 26-slot array O(n) space. It is fixed size, so it is constant.
  • Assuming lowercase input without saying so, then failing on a capital letter.
  • Using string concatenation or repeated .count() calls inside a loop, which quietly turns linear work into quadratic.

Saying it out loud

Fictional example

A clean explanation in under a minute
Candidate
If the lengths differ I can say no right away. Otherwise, sorting both strings and comparing would work in n log n.
Candidate
I can do better with counts. I add one per character of the first string and subtract one per character of the second. If a count drops below zero, the second string has an extra copy of that letter, so I return false.
Candidate
Since the lengths match, no negatives means all zeros. That is linear time, and if the input is only lowercase letters I can use a 26-slot array so the extra memory is constant.

Problems that build on this one

Once a count table feels natural, Group Anagrams asks you to turn that table into a dictionary key so many words can be sorted into buckets in one pass. Minimum Window Substring uses the same balance idea on a moving window, and Top K Frequent Elements starts from a frequency count before choosing winners. Every walkthrough is listed on the coding problems hub.

Using Natively while you drill this

When you rehearse warm-ups like this, Natively can read the prompt from a screenshot on your Mac or Windows computer and sketch an approach, which is useful for checking your own answer after you commit to it rather than before. It also transcribes the mock round, so you can see whether you actually stated the length check and the complexity. The AI assistant for coding interviews page explains the coding features.

Questions people ask

What is the fastest way to check if two strings are anagrams?

Count characters. Return false if the lengths differ, add one per character of the first string, subtract one per character of the second, and return false if any count goes negative. It runs in O(n) time.

Is sorting both strings an acceptable answer?

Yes, it is correct and short, but it costs O(n log n) time. Offer it first, then move to counting if the interviewer wants linear time.

Why is the 26-slot array O(1) space?

Its size depends on the alphabet, not on the input length. For lowercase English letters it is always 26 integers, however long the strings are.

How do you handle Unicode in Valid Anagram?

Use a dictionary instead of a fixed array, and normalize the text first so that accented letters written in different ways count as the same character. Ask how the interviewer defines a character.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP