InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Sliding Window

Permutation in String

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug