Coding Interview PatternsPermutation in String
MediumTwo Pointers
Permutation in String
Explanation & Solution
Description
Given two strings s1 and s2, return true if s2 contains a permutation of s1. In other words, return true if one of s1's permutations is a substring of s2.
Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").
Constraints
1 <= s1.length, s2.length <= 10⁴s1ands2consist of lowercase English letters only.
Approach
Two Pointers pattern
1. Handle Edge Case
- If
s1is longer thans2, no permutation ofs1can fit insides2, so returnfalseimmediately.
2. Build Frequency Arrays
- Create two arrays of size 26 (one for each lowercase letter):
freq1fors1andfreq2for the first window ofs2. - Iterate through the first
s1.lengthcharacters of both strings and populate the frequency counts.
3. Count Initial Matches
- Compare
freq1andfreq2at each of the 26 positions. - A
matchescounter tracks how many character slots have equal frequency between the two arrays. - If
matches === 26, all frequencies are equal, meaning the current window is a permutation ofs1.
4. Slide the Window Across s2
- For each new position
ifroms1.lengthtos2.length - 1: - Add the new character entering the window on the right. Increment its count in
freq2. Updatematches— if the count now equalsfreq1, increment matches; if it just exceededfreq1, decrement matches. - Remove the character leaving the window on the left. Decrement its count in
freq2. Updatematchesusing the same logic.
5. Check After Each Slide
- Before sliding, check if
matches === 26. If so, a permutation was found — returntrue. - After the loop ends, perform one final check on
matches === 26for the last window position.
6. Return the Result
- If no window matched during the entire traversal, return
false.
Key Insight
Instead of comparing two full frequency arrays (O(26)) at every step, we maintain a running matches count that updates in O(1) as each character enters and leaves the window. This keeps the overall complexity at O(n) where n is the length of s2.
Visualization
Input:
[e, i, d, b, a, o, o, o], s1 = ab
—
Press ▶ or use ← → to step through
Left (L)Right (R)WindowDone
5 steps