Detect Anagrams Without Sorting
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Write a function is_anagram(s: str, t: str) -> bool that checks whether t can be produced by permuting all characters of s—meaning every distinct letter occurs the exact same number of times in s as in t.
Sorting either input string (via sorted, .sort, or manual sorting) is disallowed. Aim for linear O(len(s) + len(t)) time by tracking per-letter counts directly.
Every character in s and t is a lowercase English letter ('a'–'z').
Examples
Example 1
Input: s = "rescue", t = "secure"
Output: True
Both strings have 6 characters and matching counts for every letter ('c': 1, 'e': 2, 'r': 1, 's': 1, 'u': 1), so rearranging "rescue" yields "secure".
Example 2
Input: s = "blush", t = "brush"
Output: False
Both strings have 5 characters, but "brush" consumes an 'r' that never appeared in "blush" while leaving 'l' unused.
Constraints
0 <= len(s), len(t) <= 2 * 10^5sandtconsist exclusively of lowercase ASCII letters ('a'through'z').- Sorting either string is prohibited.
Step-by-step walkthrough
Understand what makes two strings anagrams
We receive two strings
sandtconsisting solely of lowercase English letters ('a'through'z'), and we need to returnTruewhentis a permutation ofs(andFalseotherwise) without sorting either string.Two strings are anagrams if and only if every distinct character appears the exact same number of times in both strings, regardless of position. That gives us two immediate baseline checks:
- If
len(s) != len(t), their letter counts cannot match, so we returnFalseright away. - Two empty strings (
""and"") have count0for every letter, so they evaluate toTrue.
- If
Why naive non-sorting approaches are too slow or wrong
Without sorting, a tempting direct idea is to loop over every character in
s, locate a matching character int, and cross it off so it cannot be reused:s = "blush", t = "brush" 1. take 'b' from s -> find and cross off 'b' in "brush" -> remaining: "rush" 2. take 'l' from s -> 'l' is not in "rush" -> return FalseCrossing off characters is right in spirit, yet each search and removal scans up to
ncharacters oft. Acrossncharacters ofs, that takesO(n^2)time—roughly10billion operations whenn = 100,000. Meanwhile, quick shortcuts likeset(s) == set(t)ignore duplicates ("aab"and"abb"share the set{'a', 'b'}), and summing character codes collides ("ac"and"bb"have the same sum).Key idea: a 26-slot frequency balance table
Position does not matter in an anagram—only how many copies of each of the 26 letters
'a'through'z'appear. Because lowercase ASCII letters sit contiguously in character-code order, subtractingord("a")converts any letterchinto a list index from0to25:letter ch: 'a' 'b' 'c' ... 'z' ord(ch): 97 98 99 ... 122 ord(ch) - ord('a'): 0 1 2 ... 25Even better, we do not need two separate 26-element lists. We maintain a single balance list
counts = [0] * 26, deposit+1for every letter ins, and withdraw-1for every letter int. The two strings are anagrams if and only if every slot returns to0.Count available letters from s
We check
len(s) != len(t)first—both becauselen(...)on a Python string runs inO(1)time and because our second pass relies on equal lengths. Then we scansonce and deposit+1into each letter's slot:# Phase 1: Anagrams must have the exact same total number of characters. if len(s) != len(t): return False # counts: 26-slot frequency balance table; index 0 tracks 'a', ..., index 25 tracks 'z'. counts = [0] * 26 # Phase 2: Deposit +1 for every letter that appears in s. for ch in s: index = ord(ch) - ord("a") counts[index] += 1Spend letters on t and use the zero-sum invariant
Next we scan
tand subtract1from each letter's slot. Ifcounts[index]ever drops below0,thas used more copies of that letter thanssupplied, so we immediately returnFalse.What if we finish the entire loop over
tand no slot ever went negative—could some slot still be> 0? Check the sum of all 26 slots:- Before scanning
t, the 26 numbers incountsadd up tolen(s). - Scanning
tsubtracts1exactlylen(t)times, and we already verifiedlen(s) == len(t), so the final 26 numbers must sum tolen(s) - len(t) = 0. - If none of the 26 numbers is negative (
counts[i] >= 0for alli) and their sum is0, then every single slot must be0—because if even one slot were+1or higher, no negative number would exist to cancel it back down to0.
So we can return
Trueright after the loop without scanningcountsa final time!# Phase 3: Spend -1 for every letter in t; a negative count means t over-uses that letter. for ch in t: index = ord(ch) - ord("a") counts[index] -= 1 if counts[index] < 0: return False # Because len(s) == len(t), total deposits equal total withdrawals (net sum 0). # Since no slot ever dropped below 0, every single slot must now equal 0. return True- Before scanning
Walk through both examples
Let's trace the non-zero slots on both examples:
Example 1: s = "rescue", t = "secure" (len 6 == 6) After scanning s ("rescue"): c:1 e:2 r:1 s:1 u:1 (all other letters: 0) Scanning t ("secure"): 's' -> s:0 'e' -> e:1 'c' -> c:0 'u' -> u:0 'r' -> r:0 'e' -> e:0 No slot ever dropped below 0 -> return True Example 2: s = "blush", t = "brush" (len 5 == 5) After scanning s ("blush"): b:1 h:1 l:1 s:1 u:1 (r is 0) Scanning t ("brush"): 'b' -> b:0 'r' -> r drops from 0 to -1 -> immediately return False!Notice how Example 2 exits on the second character of
twithout even inspecting'u','s', or'h'.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def is_anagram(s: str, t: str) -> bool: # Phase 1: Anagrams must have the exact same total number of characters. if len(s) != len(t): return False # counts: 26-slot frequency balance table; index 0 tracks 'a', ..., index 25 tracks 'z'. counts = [0] * 26 # Phase 2: Deposit +1 for every letter that appears in s. for ch in s: index = ord(ch) - ord("a") counts[index] += 1 # Phase 3: Spend -1 for every letter in t; a negative count means t over-uses that letter. for ch in t: index = ord(ch) - ord("a") counts[index] -= 1 if counts[index] < 0: return False # Because len(s) == len(t), total deposits equal total withdrawals (net sum 0). # Since no slot ever dropped below 0, every single slot must now equal 0. return True✅ Submit now — all tests should pass.
Intuition & how it works
Imagine dumping all the letter tiles of the first word s into 26 labeled bins (a through z), then building the second word t one letter at a time by taking one tile out of the matching bin. Two words are anagrams (words formed by rearranging the exact same letters with matching counts) if and only if both words have the same total number of tiles and you never reach into an empty bin while building t.
Sorting both strings and checking sorted(s) == sorted(t) is disallowed here and would cost O(n log n) time anyway. Crossing off each character of s by scanning t avoids sorting, but scanning t repeatedly takes O(n^2) time and stalls on long strings. Simpler-looking shortcuts fail outright: comparing set(s) == set(t) ignores multiplicity ("aab" vs "abb"), and comparing the sum or bitwise XOR of Unicode code points (the numeric integer IDs that ord(ch) returns for characters) suffers from collisions such as "ac" and "bb" both summing to 97 + 99 = 98 + 98 = 196. A fixed 26-slot frequency array (a list where each index stores how many copies of one character remain) tracks exact counts in a single pass over each string.
Let's trace s = "blush" and t = "brush" (Example 2):
- Both strings have length
5, so they pass the initial length check. - Scanning
s = "blush"increments bins'b','l','u','s', and'h'to1(while bin'r'stays0). - Scanning
t = "brush"decrements bin'b'from1to0, then hits'r': subtracting1from bin'r'drops it from0to-1, immediately provingtover-uses'r'and returningFalse—whereas on Example 1 ("rescue"and"secure"),'e'climbs to2duringsand drops2 -> 1 -> 0duringt, returningTrue.
Complexity
Let n be the length of s (when len(s) != len(t), Python's O(1) string-length check returns False immediately before any loop runs).
- Time: O(n). We read each of the
ncharacters insonce and at mostncharacters intonce, doing oneO(1)subtractionord(ch) - ord("a")and oneO(1)list update per character. - Space: O(1) auxiliary space. Regardless of whether
sandthold5characters or200,000characters,countsalways holds 26 integers.
Edge cases
- Empty strings (
"",""): lengths match (0 == 0), neither loop executes, and the function returnsTrue. - Different lengths (
"a"vs"aa","abc"vs"abcc"): rejected inO(1)time bylen(s) != len(t). - Same unique letters, different multiplicities (
"aab"vs"abb"): lengths match,'a'ends at+1while the second'b'pushes bin'b'to-1, returningFalse. - Identical or reversed strings (
"rescue"vs"rescue","abc"vs"cba"): every increment is matched by an exact decrement, returningTrue. - Non-lowercase characters if constraints were relaxed: in Python, negative indices wrap around from the back of a list! Because
ord("Z") - ord("a")is90 - 97 = -7,counts[-7]silently accessescounts[19](the slot for't'), sois_anagram("t", "Z")would evaluate toTruewithout raisingIndexError. Whenever inputs are not guaranteed to be'a'–'z', use a dictionary instead of a 26-slot list.
Common mistakes
- Omitting
len(s) != len(t)while keeping only the< 0check. Without the length check,s = "abc"andt = "ab"never drive any slot negative, so the function would falsely returnTrueunless you also checkall(c == 0 for c in counts)at the end. - Comparing
set(s) == set(t). Sets discard duplicate counts, falsely accepting"aaab"and"abbb". - Summing or XORing
ord(ch)values. Distinct letter pairs can share sums and XORs ("ad"and"bc"both sum to197;"aabb"and"ccdd"both XOR to0). - Calling
s.count(ch) != t.count(ch)inside a loop overs. Each.count(ch)call scans the entire string inO(n)time, turning anO(n)check intoO(n^2)when letters repeat or differ only near the end.
Alternative approaches
- Hash map (
dict) of character counts. Incrementcounts[ch] = counts.get(ch, 0) + 1forsand decrement fort. Runs inO(n)average time andO(k)space forkdistinct characters, and safely handles uppercase letters, digits, punctuation, and arbitrary Unicode without negative-index wraparound. collections.Counter(s) == collections.Counter(t). Builds two frequency dictionaries in C and compares them inO(n)time. Clean in production Python, though interviewers asking for a non-sorting solution typically want to see explicit counting logic.
Follow-up questions
-
How would your implementation change if inputs could include uppercase letters, punctuation, or arbitrary Unicode text? Replace the 26-slot list with a Python dictionary
counts: Dict[str, int] = {}so any character can serve as a key inO(n)time andO(k)space (forkunique characters). Before checking lengths or counting, apply Unicode normalization (converting visually identical representations—such as"é"stored as one code point versus"e"plus a combining accent—into a single standard form viaunicodedata.normalize("NFC", text)). If the check should ignore case, call.casefold()beforelen(s) != len(t), since casefolding can alter string length (for example German"ß".casefold()becomes"ss"). -
Given a list of words, how can you partition them into anagram groups in linear total character time without sorting? Map every word to a canonical key (a unique representation shared by all members of the same equivalence group and no others): count its 26 letters in
counts = [0] * 26and convert that list to an immutabletuple(counts)so it can serve as a dictionary key ingroups[tuple(counts)].append(word). Forwwords withLtotal characters across all words, this runs inO(L + 26 * w)time—avoiding theO(L log M)cost of sorting words of lengthM. -
How would you locate every starting index in a long document where a substring forms an anagram of a given pattern? Use a fixed-size sliding window (a contiguous slice of fixed length
len(p)that advances right one character at a time by adding the entering character on the right and removing the leaving character on the left). Maintain the 26-slot balance between patternpand the current window along with an integermismatchestracking how many of the 26 slots are non-zero; each shift updates at most two slots and adjustsmismatchesinO(1)time, finding every match across a document of lengthninO(n)total time andO(1)extra space.
Follow-up questions
- How would your implementation change if inputs could include uppercase letters, punctuation, or arbitrary Unicode text?
- Given a list of words, how can you partition them into anagram groups in linear total character time without sorting?
- How would you locate every starting index in a long document where a substring forms an anagram of a given pattern?
Similar questions
- Python Semantics and Web Protocol Fundamentals
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One