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^5
  • s and t consist exclusively of lowercase ASCII letters ('a' through 'z').
  • Sorting either string is prohibited.

Step-by-step walkthrough

  1. Understand what makes two strings anagrams

    We receive two strings s and t consisting solely of lowercase English letters ('a' through 'z'), and we need to return True when t is a permutation of s (and False otherwise) 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 return False right away.
    • Two empty strings ("" and "") have count 0 for every letter, so they evaluate to True.
  2. 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 in t, 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 False
    

    Crossing off characters is right in spirit, yet each search and removal scans up to n characters of t. Across n characters of s, that takes O(n^2) time—roughly 10 billion operations when n = 100,000. Meanwhile, quick shortcuts like set(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).

  3. 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, subtracting ord("a") converts any letter ch into a list index from 0 to 25:

    letter ch:          'a'   'b'   'c'  ...  'z'
    ord(ch):             97    98    99  ...  122
    ord(ch) - ord('a'):   0     1     2  ...   25
    

    Even better, we do not need two separate 26-element lists. We maintain a single balance list counts = [0] * 26, deposit +1 for every letter in s, and withdraw -1 for every letter in t. The two strings are anagrams if and only if every slot returns to 0.

  4. Count available letters from s

    We check len(s) != len(t) first—both because len(...) on a Python string runs in O(1) time and because our second pass relies on equal lengths. Then we scan s once and deposit +1 into 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] += 1
    
  5. Spend letters on t and use the zero-sum invariant

    Next we scan t and subtract 1 from each letter's slot. If counts[index] ever drops below 0, t has used more copies of that letter than s supplied, so we immediately return False.

    What if we finish the entire loop over t and no slot ever went negative—could some slot still be > 0? Check the sum of all 26 slots:

    • Before scanning t, the 26 numbers in counts add up to len(s).
    • Scanning t subtracts 1 exactly len(t) times, and we already verified len(s) == len(t), so the final 26 numbers must sum to len(s) - len(t) = 0.
    • If none of the 26 numbers is negative (counts[i] >= 0 for all i) and their sum is 0, then every single slot must be 0—because if even one slot were +1 or higher, no negative number would exist to cancel it back down to 0.

    So we can return True right after the loop without scanning counts a 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
    
  6. 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 t without even inspecting 'u', 's', or 'h'.

  7. 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):

  1. Both strings have length 5, so they pass the initial length check.
  2. Scanning s = "blush" increments bins 'b', 'l', 'u', 's', and 'h' to 1 (while bin 'r' stays 0).
  3. Scanning t = "brush" decrements bin 'b' from 1 to 0, then hits 'r': subtracting 1 from bin 'r' drops it from 0 to -1, immediately proving t over-uses 'r' and returning False—whereas on Example 1 ("rescue" and "secure"), 'e' climbs to 2 during s and drops 2 -> 1 -> 0 during t, returning True.

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 n characters in s once and at most n characters in t once, doing one O(1) subtraction ord(ch) - ord("a") and one O(1) list update per character.
  • Space: O(1) auxiliary space. Regardless of whether s and t hold 5 characters or 200,000 characters, counts always holds 26 integers.

Edge cases

  • Empty strings ("", ""): lengths match (0 == 0), neither loop executes, and the function returns True.
  • Different lengths ("a" vs "aa", "abc" vs "abcc"): rejected in O(1) time by len(s) != len(t).
  • Same unique letters, different multiplicities ("aab" vs "abb"): lengths match, 'a' ends at +1 while the second 'b' pushes bin 'b' to -1, returning False.
  • Identical or reversed strings ("rescue" vs "rescue", "abc" vs "cba"): every increment is matched by an exact decrement, returning True.
  • Non-lowercase characters if constraints were relaxed: in Python, negative indices wrap around from the back of a list! Because ord("Z") - ord("a") is 90 - 97 = -7, counts[-7] silently accesses counts[19] (the slot for 't'), so is_anagram("t", "Z") would evaluate to True without raising IndexError. 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 < 0 check. Without the length check, s = "abc" and t = "ab" never drive any slot negative, so the function would falsely return True unless you also check all(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 to 197; "aabb" and "ccdd" both XOR to 0).
  • Calling s.count(ch) != t.count(ch) inside a loop over s. Each .count(ch) call scans the entire string in O(n) time, turning an O(n) check into O(n^2) when letters repeat or differ only near the end.

Alternative approaches

  • Hash map (dict) of character counts. Increment counts[ch] = counts.get(ch, 0) + 1 for s and decrement for t. Runs in O(n) average time and O(k) space for k distinct 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 in O(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 in O(n) time and O(k) space (for k unique 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 via unicodedata.normalize("NFC", text)). If the check should ignore case, call .casefold() before len(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] * 26 and convert that list to an immutable tuple(counts) so it can serve as a dictionary key in groups[tuple(counts)].append(word). For w words with L total characters across all words, this runs in O(L + 26 * w) time—avoiding the O(L log M) cost of sorting words of length M.

  • 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 pattern p and the current window along with an integer mismatches tracking how many of the 26 slots are non-zero; each shift updates at most two slots and adjusts mismatches in O(1) time, finding every match across a document of length n in O(n) total time and O(1) extra space.

Follow-up questions

Similar questions

More Pilot interview questions

All 2 Pilot questions →