KatInterview

First Window Matching a Letter-Frequency Snapshot

StringsAuto-graded · 26 test cases
MediumAuto-gradedStringssliding-windowhash-maptwo-pointers

Last 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 equals pattern character-for-character also qualifies.
  • Return the leftmost (minimum) valid starting index (0-indexed), or -1 when 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^5
  • 1 <= 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.