First Window Matching a Letter-Frequency Snapshot
StringsAuto-graded · 26 test casesLast updated
Tests fixed-size sliding window technique with O(1) per-step character-count bookkeeping to locate the leftmost permutation of a pattern inside a longer string.
You are given two strings, text and pattern, both consisting of lowercase English letters 'a' through 'z'.
A window in text is compatible with pattern if it has exactly the same length as pattern and contains every letter in exactly the same quantity — order does not matter. In other words, the window is some rearrangement (permutation) of pattern.
Return the smallest starting index of a compatible window in text. If no compatible window exists, return -1.
Rules
- The window must have length exactly
len(pattern). - Every letter must appear the same number of times in the window as it does in
pattern. A window that equalspatterncharacter-for-character also qualifies. - Return the leftmost (minimum) valid starting index (0-indexed), or
-1when no valid window exists. - If
len(pattern) > len(text), no window of the required length can fit, so return-1.
Constraints
1 <= len(text) <= 10^51 <= len(pattern) <= 10^5- Both strings consist only of lowercase English letters (
'a'–'z').
Examples
Example 1
Input: first_permutation_index('cbaebabacd', 'abc')
Output: 0
Example 2
Input: first_permutation_index('eidbaooo', 'ab')
Output: 3
Example 3
Input: first_permutation_index('aaa', 'aaaa')
Output: -1
Hints
Hint 1
Two strings are permutations of each other if and only if their per-letter counts are identical. Think about how to represent and compare those counts efficiently.
Hint 2
A window that slides one step to the right gains one character on the right and loses one character on the left. You don't need to recount the entire window — only two letters change.
Hint 3
Instead of comparing all 26 counters at every step, maintain a single integer that tracks how many letters are currently mismatched between the window and the pattern. A match occurs when that integer reaches zero.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Reframing the problem
Two strings of equal length are permutations of each other when their character-frequency profiles are identical. Every candidate window has the same fixed length m = len(pattern), so the search reduces to: slide a window of width m across text left to right and stop at the first position where its frequency profile matches pattern's profile.
Avoiding full recomputation at every step
A naive approach recomputes or fully compares 26 counters at every position, costing O(26 · n). That is fast enough in practice, but there is a cleaner way that makes the per-step cost visibly O(1).
Keep one extra integer, diff, equal to the number of letters c (out of 26) where the window's count of c differs from the pattern's count of c. The window is a valid permutation exactly when diff == 0.
When the window slides one step:
- One letter
aenters on the right:have[a]increases by 1. - One letter
bexits on the left:have[b]decreases by 1.
Only those two counters change. For each changed counter, check the match status before and after the update:
- If the letter was matched (
have == need) before the change, it is now mismatched:diff += 1. - If the letter is matched (
have == need) after the change, it is now matched:diff -= 1.
Both checks are needed independently. A letter can transition from matched → unmatched, unmatched → matched, or unmatched → a different unmatched value (in which case the two adjustments cancel out, correctly leaving diff unchanged).
When a == b the window's multiset is unchanged, so the update is skipped entirely.
Algorithm walkthrough
- If
m > n, return-1immediately — no window of the required length fits. - Build
needby counting letters inpattern. Buildhaveby counting letters in the first windowtext[0:m]. - Compute the initial
diffover all 26 letters. Ifdiff == 0, return0. - For each index
ifrommton - 1, slide the window and updatehaveanddiffas described. Ifdiff == 0, returni - m + 1. - If the loop ends without a match, return
-1.
Windows are scanned in increasing order of starting index, so the first diff == 0 encountered is the leftmost match.
Why it is correct
Invariant: after processing index i, have exactly records the letter counts of text[i - m + 1 .. i], and diff equals the number of letters where have and need disagree.
- The invariant holds after initialization by direct construction.
- Each slide updates at most two counters. The before/after pattern correctly removes each letter's old contribution to
diffand adds its new one. All other letters are unaffected. diff == 0is equivalent to all 26 counters matching, which is equivalent to the window being a permutation ofpattern.
Edge cases
len(pattern) > len(text): caught by the early return.len(pattern) == len(text): only one window exists; the loop never runs, and the answer comes from the initialdiffcheck.- Match at index 0: caught before the loop.
- Repeated letters (e.g.,
pattern = "aab"): per-letter counts handle multiplicity correctly —"abb"does not match. - Incoming letter equals outgoing letter (
a == b): thea != bguard prevents a spuriousdifffluctuation.
Complexity
- Time: O(n + m). Counting
patternand the initial window is O(m). The initialdiffcomputation is O(26). Each of the at mostn − mslides is O(1). - Space: O(1) extra — two fixed-size arrays of 26 integers and a handful of scalars.
Full solution
def first_permutation_index(text: str, pattern: str) -> int:
n, m = len(text), len(pattern)
if m > n:
return -1
# Target letter frequencies from pattern.
need = [0] * 26
for ch in pattern:
need[ord(ch) - 97] += 1
# Letter frequencies in the initial window of length m.
have = [0] * 26
for ch in text[:m]:
have[ord(ch) - 97] += 1
# diff = number of distinct letters where have[c] != need[c].
diff = sum(1 for c in range(26) if need[c] != have[c])
if diff == 0:
return 0
for i in range(m, n):
a = ord(text[i]) - 97 # letter entering the window on the right
b = ord(text[i - m]) - 97 # letter leaving the window on the left
if a != b:
# Update the incoming letter.
if have[a] == need[a]: # was matched — about to become unmatched
diff += 1
have[a] += 1
if have[a] == need[a]: # now matched
diff -= 1
# Update the outgoing letter.
if have[b] == need[b]: # was matched — about to become unmatched
diff += 1
have[b] -= 1
if have[b] == need[b]: # now matched
diff -= 1
if diff == 0:
return i - m + 1
return -1