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^5textandpatternconsist of lowercase ASCII letters ('a'–'z').- Expected time complexity is
O(len(text) + len(pattern)).
Step-by-step walkthrough
Understand the goal and boundary cases
An anagram of
patternis 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
textwhose length equalswindow_len = len(pattern)can possibly match. We want the smallest starting index of such a substring, or-1if none exists.Let's settle two quick boundary cases right away:
- If
window_len == 0(an emptypattern), the empty substring at index0has the exact same empty counts, so we return0(matchingtext.find("")in Python). - If
window_len > len(text),textis too short to hold even one full window, so we return-1.
- If
Why recounting every window wastes work
A brute-force solution slices every length-
ksubstringtext[i : i + k], sorts it (or counts its letters from scratch), and compares it againstpattern: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 -1Sorting each window takes
O(k log k)time acrossn - k + 1windows, orO(n * k log k)overall (and recounting from scratch still takesO(n * k)). Look at why that is wasteful ontext = "xycabzba"withk = 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..2to1..3, the middlek - 1characters do not change at all — only'x'leaves on the left and'a'enters on the right!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 ofch. - Negative
balance[ch]means the window has too many copies ofch(either surplus copies of a pattern letter, or a letter that never appeared inpattern). - Zero means
chhas the exact right count!
Here is the trick that makes checking for an anagram
O(1): wheneverbalance[ch]reaches0, we deletechfrombalance. That preserves a clean invariant:balanceholds only mismatched characters, so the current window is an anagram ofpatternif and only iflen(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- Positive
Slide the window across `text`
First, we load
patternintobalanceby adding+1for each character inpattern(representing an empty window that still needs every character ofpattern).Then we advance the window's right endpoint
rightfrom0tolen(text) - 1:- Enter on the right:
text[right]enters the window, supplying one copy, so we adjust its balance by-1. - Leave on the left (once
right >= window_len): the window now spanswindow_len + 1positions, sotext[right - window_len]falls off the left edge. Because we lost one copy from the window, we adjust its balance by+1. - Check for a match (once
right >= window_len - 1): indices0 .. window_len - 1form the very first full window of lengthwindow_len. Wheneverlen(balance) == 0, every character matchespatternand the window starts atright - 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 = 2Notice how
"abb"(right=2) and"bba"(right=3) have the right set of letters ('a'and'b'), yetbalancestays{'a': 1, 'b': -1}until the surplus'b'leaves and the second'a'enters atright = 4!- Enter on the right:
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
2without needing to inspect the remaining characters"zba".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
balancedictionary scans thekcharacters ofpatternonce, and the sliding loop scans thencharacters oftextat most once (stopping early at the first match), performing at most twoO(1)dictionary updates and oneO(1)len(balance)check per index. - Space: O(s) (which is
O(1)when the alphabet is fixed to 26 lowercase letters, and at mostO(k)for general alphabets). Because we delete keys as soon as their difference returns to0,balanceonly ever stores characters currently inpatternor in the activek-character window.
Edge cases
- Pattern longer than text (
len(pattern) > len(text)): no window of lengthkcan fit insidetext, so we immediately return-1. - Empty pattern (
pattern == ""): returns0, because the empty prefix at index0has matching (empty) character counts; conversely,text == ""with a nonemptypatternhitswindow_len > len(text)and returns-1. - Match at the very first or very last index:
right = window_len - 1checks index0, andright = len(text) - 1checks the final windowlen(text) - window_len. - Right letters with wrong multiplicities (
text = "abbaab",pattern = "aab"):"abb"leavesbalance = {'a': 1, 'b': -1}, which is non-empty, so only"baa"at index2matches. - Extra copies of a needed letter (
text = "bbbab",pattern = "ab"): surplus'b's pushbalance['b']negative until they slide out on the left. - Characters absent from
pattern(text = "abzcab",pattern = "abc"):'z'enters withbalance['z'] = -1, blocking any match until'z'slides outksteps 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 toFalse! If you leave0values inside a plain dictionary and checkbalance == {}, 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 lengthkoccupies indicesright - k + 1throughrightinclusive, so the element that just fell off the left side istext[right - k](nottext[right - k + 1]). - Checking for a match before the window is full: if
pattern = "ab"andtext = "a...",balanceis still non-empty atright = 0, and guarding withright >= window_len - 1ensures we only report full windows of lengthk. - Buggy "remaining needed characters" counter: if you keep an integer
needed = kand decrement it on every pattern letter,"bbbab"with"ab"decrementsneededtwice on"bb"and falsely reports index0. 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', storepat_counts = [0] * 26andwin_counts = [0] * 26and checkwin_counts == pat_countsat 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 thanlen(balance) == 0and 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 whenkis 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 indextext[right - k], we read the file in small blocks (say 64 KB) and keep only the most recentkcharacters in a ring buffer — a fixed-sizecollections.deque(maxlen=k)that automatically drops the oldest character when a new one is pushed — keeping RAM usage atO(k)regardless of file size. - What state do you need to maintain if the text arrives incrementally in arbitrary-length network chunks? Wrap
balance, adeque(maxlen=k)holding the current window's characters, and a runningtotal_seencounter inside a statefulStreamingAnagramFinderobject. 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 indextotal_seen - k. - How would you parallelize the search across a cluster of machines when a match might straddle two storage blocks? Partition
textintoMcontiguous shardsS_0, S_1, ..., S_{M-1}, and have workerjappend the firstk - 1characters of shardS_{j+1}to the end ofS_jso anyk-character anagram straddling the boundary betweenS_jandS_{j+1}is fully visible to workerj. Every worker runsfind_first_anagram_occurrenceindependently on its local shard (adding its shard's starting offset) and reports either its earliest global index orNone. The coordinator returns the minimum index reported — and as soon as workerjfinds a match while workers0 .. j-1reportNone, any remaining workersj+1 .. M-1can be canceled immediately.
Follow-up questions
- How can you search a multi-gigabyte file on disk without loading the entire text into RAM?
- What state do you need to maintain if the text arrives incrementally in arbitrary-length network chunks?
- How would you parallelize the search across a cluster of machines when a match might straddle two storage blocks?
Similar questions
- Insertion-Ordered Set with O(1) Snapshot Iterators
- Ordered Allow/Deny Cancellation of an IPv4 CIDR
- Minimum Travel Time Across a Speed-Limited Grid
- Five-Minute Window Average for Streaming Load
- Trailing Five-Minute In-Memory QPS Tracker
- Minimal CIDR Cover for an IPv4 Range
More Databricks interview questions
- k-Streak Win Detection on a Rectangular Grid Medium
- Referral-Aware Customer Revenue Tracker Medium
- Snapshot-Isolated Dynamic Set Hard Pro
- Bounded-Memory Rolling Hit Counter Medium Pro
- Background Intro, Workplace Disagreement, and Flagship Project Medium Pro
- Key-Value Store with Sliding-Window Read and Write Rates Medium Pro
- Behavioral Recruiter Screen Medium Pro
- Trailing Five-Minute In-Memory QPS Tracker Medium Pro
- Bounded-Ply Forced Win Search on Generalized Tic-Tac-Toe Medium Pro
- Enterprise Messaging Core: Sequenced Timelines and Versioned Membership Hard Pro