Coding Interview PatternsMinimum Window Subsequence
HardSliding Window
Minimum Window Subsequence
Explanation & Solution
Description
Given strings s1 and s2, return the minimum contiguous substring of s1 such that s2 is a subsequence of the substring. If there is no such window, return an empty string "".
If there are multiple minimum-length windows, return the one that occurs first (leftmost).
Input: s1 = "abcdebdde", s2 = "bde"
Output: "bcde"
Explanation: "bcde" is the shortest substring of s1 where "bde" is a subsequence: b→d→e. Another candidate "bdde" has the same length but starts later.
Constraints
1 <= s1.length <= 2 * 10^41 <= s2.length <= 100s1ands2consist of lowercase English letters.
Approach
Sliding Window pattern
1. Forward Pass — Find a Subsequence Match
- Starting from index
i, scan forward throughs1to find all characters ofs2in order. - Use pointer
jfors2: whenevers1[start] === s2[j], advancej. - If
jreachess2.length, we found a valid window ending just beforestart. - If
jnever reachess2.length, no more matches are possible — stop.
2. Backward Pass — Optimize the Window
- After finding a match ending at index
start - 1, trace backward throughs1from that end. - Match
s2characters in reverse: starting froms2[s2.length - 1]back tos2[0]. - This finds the rightmost (latest) starting position for the subsequence, which gives the shortest window ending at this position.
- The result is the optimized window
[end, start).
3. Update the Minimum
- Compare the current window length
start - endwithminLen. - If shorter, update
minLenandminStart.
4. Advance and Repeat
- Set
i = end + 1to search for the next potential window. - Repeat until no more subsequence matches are found.
5. Return the Result
- If a valid window was found, return the substring from
minStartwith lengthminLen. - Otherwise return an empty string.
Key Insight
- The critical insight is the backward optimization: after finding any valid window, tracing backward from the end gives the tightest possible window for that endpoint. This avoids checking all O(n^2) substrings and is much more efficient than a brute-force approach.
Time
O(n * m) where n = `s1.length` and m = `s2.length`. Each forward+backward pass takes at most O(n), and we advance `i` each iteration.Space
O(1)only a few pointers.Visualization
Input:
[a, b, c, d, e, b, d, d, e], s2 = bde
—
Press ▶ or use ← → to step through
Left (L)Right (R)WindowDone
20 steps