InterviewPrepKit

Home / Coding / Sliding Window

Permutation in String

medium Original β†—
Solving tips
  • Key insight: 'contains a permutation of s1' means some length-len(s1) window of s2 has an identical 26-letter histogram, so this is a fixed-size window.
  • Build need and window count arrays over the first m chars, then slide adding s2[right] and removing s2[right-m], comparing histograms.
  • Optimize O(26*n) to O(n) by maintaining a 'matches' counter of how many of the 26 letters currently agree, updating it around each count change.
  • Target O(n) time and O(1) space; pitfalls are forgetting the m>n early exit and not testing the initial window before the first slide.

Problem

You are given two strings s1 and s2. Decide whether s2 contains any permutation of s1 as a contiguous substring β€” in other words, whether some window of s2 uses exactly the same characters as s1, with exactly the same multiplicities, in any order. Return True if such a window exists, otherwise False.

Examples

  • s1 = "ab", s2 = "eidbaooo" β†’ True β€” the window "ba" (indices 3–4) is a rearrangement of "ab".
  • s1 = "ab", s2 = "eidboaoo" β†’ False β€” no two adjacent characters of s2 are exactly {a, b}.
  • s1 = "adc", s2 = "dcda" β†’ True β€” the window "cda" (indices 1–3) is a permutation of "adc".

Constraints

  • 1 <= len(s1), len(s2) <= 10^4
  • Both strings consist of lowercase English letters only.
  • The 10^4 bound rules out re-scanning each window from scratch; an O(n) or O(26Β·n) pass is expected.

Think about it first

Hint 1 Two strings are permutations of each other exactly when they have identical character counts. You never need to generate actual permutations.
Hint 2 Every candidate substring has exactly `len(s1)` characters. That means the window size is fixed β€” you are sliding a window of constant width across `s2`.
Hint 3 Keep a count array for the current window. When the window slides one step, only two characters change: one enters on the right, one leaves on the left. Update the counts (or a running "how many of the 26 letters match" tally) in O(1) and check for a full match.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.