First Anagram Substring Index

Medium · Coding & Algorithms · Backend Engineer · Technical Screen

Problem Statement

You receive two strings, text and pattern. Locate the earliest 0-based index i where the contiguous slice text[i : i + len(pattern)] forms a permutation of pattern, and return i. When no contiguous slice of text is a permutation of pattern, return -1.

Two strings are permutations (anagrams) of one another precisely when every character appears the same number of times in both strings, regardless of character ordering. By convention, an empty pattern ("") matches the empty prefix at index 0, whereas a pattern longer than text cannot match anywhere and produces -1.

Examples

Example 1

Input:  text = "xycabzba", pattern = "abc"
Output: 2

Walk-through: Inspecting length-3 slices from left to right gives "xyc" (index 0), "yca" (index 1), and "cab" (index 2). "cab" contains one 'a', one 'b', and one 'c', making it the leftmost permutation of "abc".

Example 2

Input:  text = "abbcaba", pattern = "aab"
Output: 4

Walk-through: A matching slice must hold two 'a's and one 'b'. Index 0 ("abb") has the right distinct letters with inverted multiplicities, and indices 1..3 contain 'c' or surplus 'b's. Index 4 ("aba") is the earliest valid match.

Example 3

Input:  text = "planet", pattern = "stone"
Output: -1

Walk-through: Neither length-5 slice ("plane" or "lanet") has the required letter counts, so -1 is returned.

Constraints

  • 0 <= len(text), len(pattern) <= 2 * 10^5
  • text and pattern consist of lowercase ASCII letters ('a'–'z').
  • Expected time complexity is O(len(text) + len(pattern)).

Step-by-step walkthrough

  1. Understand the goal and boundary cases

    An anagram of pattern is any string made of the exact same characters with the exact same counts, possibly rearranged (for example, "cba" and "bac" are anagrams of "abc", while "abb" is not).

    Because rearranging characters never changes a string's length, only substrings of text whose length equals window_len = len(pattern) can possibly match. We want the smallest starting index of such a substring, or -1 if none exists.

    Let's settle two quick boundary cases right away:

    • If window_len == 0 (an empty pattern), the empty substring at index 0 has the exact same empty counts, so we return 0 (matching text.find("") in Python).
    • If window_len > len(text), text is too short to hold even one full window, so we return -1.
  2. Why recounting every window wastes work

    A brute-force solution slices every length-k substring text[i : i + k], sorts it (or counts its letters from scratch), and compares it against pattern:

    def brute_force(text: str, pattern: str) -> int:
        k = len(pattern)
        target = sorted(pattern)
        for start in range(len(text) - k + 1):
            if sorted(text[start : start + k]) == target:
                return start
        return -1
    

    Sorting each window takes O(k log k) time across n - k + 1 windows, or O(n * k log k) overall (and recounting from scratch still takes O(n * k)). Look at why that is wasteful on text = "xycabzba" with k = 3:

    Window 0 (indices 0..2):  [x  y  c] a  b  z  b  a
    Window 1 (indices 1..3):   x [y  c  a] b  z  b  a
                                  ^^^^
                         'y' and 'c' stayed inside!
    

    When a sliding window (a fixed-length view moving one position right at a time) steps from 0..2 to 1..3, the middle k - 1 characters do not change at all — only 'x' leaves on the left and 'a' enters on the right!

  3. Track only what is out of balance

    Instead of maintaining two separate frequency dictionaries and comparing all keys at every step, we can keep one dictionary called balance:

    balance[ch] = (count of ch in pattern) - (count of ch in current window)
    
    • Positive balance[ch] means the window still needs more copies of ch.
    • Negative balance[ch] means the window has too many copies of ch (either surplus copies of a pattern letter, or a letter that never appeared in pattern).
    • Zero means ch has the exact right count!

    Here is the trick that makes checking for an anagram O(1): whenever balance[ch] reaches 0, we delete ch from balance. That preserves a clean invariant: balance holds only mismatched characters, so the current window is an anagram of pattern if and only if len(balance) == 0!

    def _adjust_balance(balance: Dict[str, int], ch: str, delta: int) -> None:
        """Add delta to balance[ch], removing the key once its net difference hits 0."""
        new_diff = balance.get(ch, 0) + delta
        # Removing zero-difference keys guarantees `len(balance) == 0` if and only if
        # every character's window count matches `pattern`, and keeps memory bounded.
        if new_diff == 0:
            balance.pop(ch, None)
        else:
            balance[ch] = new_diff
    
  4. Slide the window across `text`

    First, we load pattern into balance by adding +1 for each character in pattern (representing an empty window that still needs every character of pattern).

    Then we advance the window's right endpoint right from 0 to len(text) - 1:

    1. Enter on the right: text[right] enters the window, supplying one copy, so we adjust its balance by -1.
    2. Leave on the left (once right >= window_len): the window now spans window_len + 1 positions, so text[right - window_len] falls off the left edge. Because we lost one copy from the window, we adjust its balance by +1.
    3. Check for a match (once right >= window_len - 1): indices 0 .. window_len - 1 form the very first full window of length window_len. Whenever len(balance) == 0, every character matches pattern and the window starts at right - window_len + 1.
    Index:     0   1   2   3   4   5
    Text:      a   b   b   a   a   b      pattern = "aab" (window_len = 3)
    
    Initial:                              balance = {'a': 2, 'b': 1}
    right=0:  [a]                         enter 'a'           -> {'a': 1, 'b': 1} (len 1 < 3)
    right=1:  [a   b]                     enter 'b' (hits 0!) -> {'a': 1}         (len 2 < 3)
    right=2:  [a   b   b]                 enter 'b'           -> {'a': 1, 'b': -1} (not empty)
    right=3:   a  [b   b   a]             enter 'a', leave 'a'-> {'a': 1, 'b': -1} (not empty)
    right=4:   a   b  [b   a   a]         enter 'a', leave 'b'-> {}  MATCH! start = 4 - 3 + 1 = 2
    

    Notice how "abb" (right=2) and "bba" (right=3) have the right set of letters ('a' and 'b'), yet balance stays {'a': 1, 'b': -1} until the surplus 'b' leaves and the second 'a' enters at right = 4!

  5. Trace Example 1

    Let's verify Example 1 (text = "xycabzba", pattern = "abc", window_len = 3):

    Start:     balance = {'a': 1, 'b': 1, 'c': 1}
    right = 0: enter 'x'             -> balance = {'a': 1, 'b': 1, 'c': 1, 'x': -1}
    right = 1: enter 'y'             -> balance = {'a': 1, 'b': 1, 'c': 1, 'x': -1, 'y': -1}
    right = 2: enter 'c' (hits 0!)   -> balance = {'a': 1, 'b': 1, 'x': -1, 'y': -1}  (window "xyc")
    right = 3: enter 'a', leave 'x'  -> 'a' and 'x' both hit 0!
                                     -> balance = {'b': 1, 'y': -1}                   (window "yca")
    right = 4: enter 'b', leave 'y'  -> 'b' and 'y' both hit 0!
                                     -> balance = {}                                  (window "cab")
               right >= 2 and len(balance) == 0 -> return 4 - 3 + 1 = 2!
    

    We immediately return 2 without needing to inspect the remaining characters "zba".

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def _adjust_balance(balance: Dict[str, int], ch: str, delta: int) -> None:
        """Add delta to balance[ch], removing the key once its net difference hits 0."""
        new_diff = balance.get(ch, 0) + delta
        # Removing zero-difference keys guarantees `len(balance) == 0` if and only if
        # every character's window count matches `pattern`, and keeps memory bounded.
        if new_diff == 0:
            balance.pop(ch, None)
        else:
            balance[ch] = new_diff
    
    
    def find_first_anagram_occurrence(text: str, pattern: str) -> int:
        window_len = len(pattern)
    
        # Phase 1: Handle empty-pattern and too-short-text boundary cases up front.
        if window_len == 0:
            return 0
        if window_len > len(text):
            return -1
    
        # Phase 2: Build initial character requirements from `pattern`.
        # balance: {char: pattern_count - window_count} for all mismatched characters.
        # Example for pattern = "aab": starts as {'a': 2, 'b': 1}.
        balance: Dict[str, int] = {}
        for ch in pattern:
            balance[ch] = balance.get(ch, 0) + 1
    
        # Phase 3: Slide a window of length `window_len` from left to right across `text`.
        for right in range(len(text)):
            # Character entering at `right` supplies 1 occurrence, so needed count drops by 1.
            entering_char = text[right]
            _adjust_balance(balance, entering_char, -1)
    
            # Once `right >= window_len`, the window temporarily has `window_len + 1` chars,
            # so evict the character that just fell off the left edge (`right - window_len`).
            if right >= window_len:
                leaving_char = text[right - window_len]
                _adjust_balance(balance, leaving_char, 1)
    
            # Why `window_len - 1`: indices 0 .. window_len - 1 form the first full window.
            # Because we scan left to right, the first empty `balance` is the leftmost match.
            if right >= window_len - 1 and len(balance) == 0:
                window_start = right - window_len + 1
                return window_start
    
        return -1
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

An anagram is a rearrangement of the exact same characters in the exact same quantities (like "silent" and "listen"). Think of pattern as a packing checklist of length k, and imagine sliding a magnifying glass k characters wide — a sliding window, meaning a fixed-size contiguous slice moving one step at a time — from left to right across text. Every character entering the right side of the magnifying glass crosses one item off our checklist (-1), and every character sliding out the left side puts one item back onto the checklist (+1). By storing these net differences in a hash map (Python dict mapping each character to pattern_count - window_count) and deleting any character whose difference hits 0, the window is an exact anagram the moment the dictionary becomes completely empty!

A naive solution slices each length-k substring text[i : i + k] and either sorts it (O(k log k)) or counts all k letters from scratch (O(k)). Because two neighboring windows overlap in k - 1 characters, recounting from scratch repeats almost the exact same work at every index, taking O(n * k) time overall. On a 200,000-character text and a 1,000-character pattern, that means roughly 200,000,000 operations instead of a single fast scan.

Let's trace a tiny example: text = "bbab", pattern = "ab" (window_len = 2). 1. Initialize balance from "ab": {'a': 1, 'b': 1}. 2. right = 0 ('b' enters): 'b' drops 1 -> 0 and is deleted -> balance = {'a': 1} (window "b", not length 2 yet). 3. right = 1 ('b' enters): 'b' drops 0 -> -1 -> balance = {'a': 1, 'b': -1} (window "bb" has one missing 'a' and one surplus 'b'). 4. right = 2 ('a' enters, text[0] = 'b' leaves): 'a' drops 1 -> 0 (deleted), and 'b' rises -1 -> 0 (deleted) -> balance = {}! The dictionary is empty, so we immediately return window_start = 2 - 2 + 1 = 1 (substring "ba").

Complexity

Let n = len(text), k = len(pattern), and s be the number of distinct characters in the current window plus pattern (at most 26 for lowercase English letters, and never more than 2 * k even for arbitrary Unicode characters).

  • Time: O(n + k). Building the initial balance dictionary scans the k characters of pattern once, and the sliding loop scans the n characters of text at most once (stopping early at the first match), performing at most two O(1) dictionary updates and one O(1) len(balance) check per index.
  • Space: O(s) (which is O(1) when the alphabet is fixed to 26 lowercase letters, and at most O(k) for general alphabets). Because we delete keys as soon as their difference returns to 0, balance only ever stores characters currently in pattern or in the active k-character window.

Edge cases

  • Pattern longer than text (len(pattern) > len(text)): no window of length k can fit inside text, so we immediately return -1.
  • Empty pattern (pattern == ""): returns 0, because the empty prefix at index 0 has matching (empty) character counts; conversely, text == "" with a nonempty pattern hits window_len > len(text) and returns -1.
  • Match at the very first or very last index: right = window_len - 1 checks index 0, and right = len(text) - 1 checks the final window len(text) - window_len.
  • Right letters with wrong multiplicities (text = "abbaab", pattern = "aab"): "abb" leaves balance = {'a': 1, 'b': -1}, which is non-empty, so only "baa" at index 2 matches.
  • Extra copies of a needed letter (text = "bbbab", pattern = "ab"): surplus 'b's push balance['b'] negative until they slide out on the left.
  • Characters absent from pattern (text = "abzcab", pattern = "abc"): 'z' enters with balance['z'] = -1, blocking any match until 'z' slides out k steps later, when its key is cleanly deleted.

Common mistakes

  • Comparing set(window) == set(pattern): sets ignore duplicates, falsely reporting "abb" as an anagram of "aab".
  • Comparing plain Python dictionaries without removing zeros: in Python, {'a': 0} == {} evaluates to False! If you leave 0 values inside a plain dictionary and check balance == {}, a valid match will fail whenever a non-pattern letter entered and later left. Deleting zero keys avoids this completely.
  • Off-by-one errors on window boundaries: when the right pointer is at right, a full window of length k occupies indices right - k + 1 through right inclusive, so the element that just fell off the left side is text[right - k] (not text[right - k + 1]).
  • Checking for a match before the window is full: if pattern = "ab" and text = "a...", balance is still non-empty at right = 0, and guarding with right >= window_len - 1 ensures we only report full windows of length k.
  • Buggy "remaining needed characters" counter: if you keep an integer needed = k and decrement it on every pattern letter, "bbbab" with "ab" decrements needed twice on "bb" and falsely reports index 0. Tracking non-zero balances per distinct character prevents surplus copies of 'b' from canceling out a missing 'a'.

Alternative approaches

  • Two 26-element integer arrays: when inputs are strictly 'a'–'z', store pat_counts = [0] * 26 and win_counts = [0] * 26 and check win_counts == pat_counts at each full window. Comparing two length-26 lists takes 26 comparisons per step (O(26 * n) = O(n)), which is slightly more work per character than len(balance) == 0 and does not generalize directly to Unicode without switching back to a dictionary.
  • Sorting every window (O(n * k log k)): four lines of code and great as a ground-truth oracle in unit tests (_brute_find), but far too slow when k is in the hundreds or thousands.

Follow-up questions

  • How can you search a multi-gigabyte file on disk without loading the entire text into RAM? Our algorithm already scans left to right in a single pass and stops at the very first match, so time scales linearly as O(n) and often much faster when an anagram appears early. Instead of loading the whole file into memory so we can index text[right - k], we read the file in small blocks (say 64 KB) and keep only the most recent k characters in a ring buffer — a fixed-size collections.deque(maxlen=k) that automatically drops the oldest character when a new one is pushed — keeping RAM usage at O(k) regardless of file size.
  • What state do you need to maintain if the text arrives incrementally in arbitrary-length network chunks? Wrap balance, a deque(maxlen=k) holding the current window's characters, and a running total_seen counter inside a stateful StreamingAnagramFinder object. Each incoming chunk simply feeds its characters one by one into the exact same enter/evict logic, so an anagram split halfway across chunk 4 and chunk 5 is detected seamlessly on the exact character that completes it at index total_seen - k.
  • How would you parallelize the search across a cluster of machines when a match might straddle two storage blocks? Partition text into M contiguous shards S_0, S_1, ..., S_{M-1}, and have worker j append the first k - 1 characters of shard S_{j+1} to the end of S_j so any k-character anagram straddling the boundary between S_j and S_{j+1} is fully visible to worker j. Every worker runs find_first_anagram_occurrence independently on its local shard (adding its shard's starting offset) and reports either its earliest global index or None. The coordinator returns the minimum index reported — and as soon as worker j finds a match while workers 0 .. j-1 report None, any remaining workers j+1 .. M-1 can be canceled immediately.

Follow-up questions

Similar questions

More Databricks interview questions

All 122 Databricks questions →