DSA Visualizer · 25 visualizationsPermutation in String
Permutation in String
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. In other words, return true if one of s1's permutations is a substring of s2.
Count the letters needed: a:1, b:1. Slide a window of length 2 across s2.
Problem
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. In other words, return true if one of s1's permutations is a substring of s2.
Examples
s2 contains "ba", which is a permutation of s1
Constraints
- 1 ≤ s1.length, s2.length ≤ 10⁴
- s1 and s2 consist of lowercase English letters
Intuition
A permutation of s1 appearing in s2 just means some window of s2, exactly s1's length, has the *same letter counts* as s1 — order doesn't matter. So slide a fixed-size window of length s1.length across s2, keeping a running letter count for the window, and compare it to s1's letter count at every position.
Brute force → Optimal
Generate every permutation of s1 and check whether each is a substring of s2.
Fixed-size sliding window with a 26-letter count array for the window, compared against s1's count array as the window slides.
Complexity
Edge cases
- s1 longer than s2: no window of that size fits, so the answer is false.
- s1 equals s2: the only possible window is the whole string, and it trivially matches itself.
Common mistakes
- Recomputing the window's full letter count from scratch at every position instead of removing the outgoing character and adding the incoming one.
- Comparing sorted substrings at every window position, which is correct but needlessly expensive compared to count arrays.