Pattern this teaches:Hashing and Frequency Maps
Valid Anagram
An easy Strings interview guide. Task statement, worked examples, intuition, and step-by-step solutions.
- Topic
- Strings
- Sheets
- 2
- Core for
- 14 roles
The problem
Two strings s and t are anagrams when one can be rearranged into the other, using every letter exactly as many times. Return true when t is an anagram of s and false when it is not.
Example 1
- Input
- s="anagram", t="nagaram"
- Output
- true
- Why
- Both strings contain three 'a's and one of 'n', 'g', 'r', 'm'.
Example 2
- Input
- s="rat", t="car"
- Output
- false
- Why
- The string s contains 't' while t contains 'c', so their character counts differ.
Constraints
- 1 <= s.length, t.length <= 5 * 10^4
- s and t consist of lowercase English letters
How to think about it
Updated 2026-09-29Two strings are anagrams if and only if they have identical length and identical character counts. A single fixed-size array acts as a balance scale: increment counts for letters in s and decrement for letters in t. If any count ends nonzero or goes negative early, the strings cannot be anagrams.
Approaches, worst first
Sort both strings
time O(n log n) · space O(n)
Sort the characters of s and t alphabetically, then check whether the two sorted sequences are identical. Sorting takes logarithmic overhead and requires copying strings in languages with immutable types.
Fixed frequency balance arrayWrite this one
time O(n) · space O(1)
Verify equal lengths first. Allocate an integer array of size 26, increment for each character in s, and decrement for each character in t. If any entry drops below zero during the second pass, return false without needing to scan the frequency table again.
Where people lose marks · 3
- Differing string lengths: if s.length != t.length, the strings can never be anagrams; checking this up front avoids false positives or unnecessary looping.
- Unicode characters outside lowercase English letters: fixed 26-element arrays overflow if characters include capitals or symbols; a hash map or larger lookup array is required when character ranges expand.
- Only checking if all characters of s are in t: ignoring frequencies fails on cases like 'aab' versus 'abb'.
Full solution
Fixed 26-slot frequency balance array: increment for s, decrement for t, bail the moment a count goes negative. Same time as sorting but O(1) space and a single pass each way.
Python
def is_anagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
counts = [0] * 26
a = ord("a")
for ch in s:
counts[ord(ch) - a] += 1
for ch in t:
idx = ord(ch) - a
counts[idx] -= 1
if counts[idx] < 0:
return False
return True
JavaScript
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const counts = new Array(26).fill(0);
const aCode = "a".charCodeAt(0);
for (const ch of s) counts[ch.charCodeAt(0) - aCode]++;
for (const ch of t) {
const idx = ch.charCodeAt(0) - aCode;
counts[idx]--;
if (counts[idx] < 0) return false;
}
return true;
}
The theory behind it
Strings — the ground this problem stands on. All Strings problems
What Strings is
A string is an ordered necklace of text characters, like letters printed along a ribbon of paper. Each character sits at an exact numeric slot, holding a glyph such as a letter, punctuation mark, or digit. In many programming languages, ribbons cannot be edited after creation, meaning changing a single character requires pressing an entirely new ribbon from scratch.
When to reach for it
Reach for string techniques when inputs consist of words, DNA sequences, serialized data formats, or sentences. Clues include questions testing palindromes, anagram matches, substring patterns, parenthesis balancing, or character frequency counts. Whenever an algorithm asks to transform capitalization, parse structured tokens, or compute edits between two phrases, string representations are the core subject.
How the pattern works
Think of characters as small integer codes ranging across standard character sets. Frequency tables with fixed sizes often replace heavy hash maps when tallying occurrences. For search tasks, maintain rolling state using character indices or sliding borders. When building output text through repeated appends, accumulate pieces inside a mutable list or string builder rather than concatenating strings directly, avoiding quadratic copy overhead.
More Strings problems
Target Roles
Core requirement for 14 roles:
Track in your role's order
Pick your target role and all 370 problems resequence to what that interview actually asks.
Start freeProblem set and role mapping as of .