Minimum Window Subsequence
Master this topic with zero to advance depth.
Minimum Window Subsequence
Given strings s1 and s2, find the minimum contiguous substring of s1 such that s2 is a subsequence of that part.
Visual Representation
s1 = "abcdebdde", s2 = "bde"
Forward (Find b...d...e):
a b c d e b d d e
^ ^ ^ (Found at index 4, end=5)
Backward (Optimize Start from index 4):
a b c d e
^ ^ (Start=1, b is at idx 1)
Result: "bcde" (Len 4)Examples
Level I: Brute Force
Intuition
For every possible starting point in s1, scan forward to see if s2 can be formed as a subsequence. If it can, record the length and update the minimum window found so far.
Thought Process
- Iterate through all indices
iins1as potential starts. - From
i, use another pointerkto scans1, andjto scans2. - If
s1[k] == s2[j], incrementj. - If
j == s2.length(), we found a window[i, k]. Its length isk - i + 1. - Track the minimum such length and the starting position.
Detailed Dry Run
| Start | s1 Scan | s2 Matched | Window | Min |
|---|---|---|---|---|
| 1 (b) | bcde | b, d, e (All) | [1, 4] | 4 |
| 5 (b) | bdde | b, d, e (All) | [5, 8] | 4 |
Level II: Dynamic Programming (O(N * M))
Intuition
We can use a 2D DP table dp[i][j] that stores the starting index of the shortest substring in s1[0...i] such that s2[0...j] is a subsequence. If no such substring exists, we store -1.
Thought Process
dp[i][0]isiifs1[i] == s2[0], elsedp[i-1][0].- For
j > 0, ifs1[i] == s2[j], thendp[i][j] = dp[i-1][j-1](we extend the subsequence start index from the previous match). - Otherwise,
dp[i][j] = dp[i-1][j](we inherit the latest start index).
Pattern: Subsequence Search with DP
Level III: Optimal (Sliding Window + Dual Scan)
Intuition
Thought Process
Unlike 'Minimum Window Substring' (set of chars), this requires subsequence (specific order). We scan forward to find any window containing the subsequence. Once found, we scan backward from the current end to find the best starting point for that specific window.
Patterns
- Forward Pass: Expand to find a valid window ending at
i. - Backward Pass: From
i, scan back to find the latest valid startj. This handles cases likeS=abbbcde, T=abcdemore accurately by skipping redundantbs at the beginning of the window.
Detailed Dry Run
| i | j | Action | Result |
|---|---|---|---|
| 1 | 0 | 'b' matched | i=2, j=1 |
| 4 | 2 | 'e' matched | Window Found! |
| Backward | - | Scan back from i=4 | Start=1 |
| Min | - | Check "bcde" | MinLen=4 |
⚠️ Common Pitfalls & Tips
The backward scan is crucial for finding the optimal start. Without it, you might find a valid window but not the minimum one starting from a later occurrence of the first character.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.