Permutation in String
Problem Statement
You are given two strings s1 and s2.
Return true if some rearrangement of s1 (a permutation) appears inside s2 as a contiguous substring. Otherwise return false.
In other words: is there a substring of s2 that uses exactly the same letters as s1, the same number of times each, in any order?
Two strings s1 and s2 of lowercase English letters.
true if a permutation of s1 is a substring of s2, otherwise false.
s2 contains "ba" (positions 3–4), which is a rearrangement of "ab".
There is a 'b' and an 'a' in s2, but they are never next to each other, so no length-2 substring has exactly one 'a' and one 'b'.
- • 1 ≤ s1.length, s2.length ≤ 10^4
- • s1 and s2 contain only lowercase English letters
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each length-m window, build a fresh count array and compare
Update two counts per slide, then compare the two 26-length arrays
Track how many of the 26 letters already have the right count
A permutation of s1 must have length m = s1.length. So check every substring of s2 of length m: count its letters from scratch and compare with the counts of s1.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.