Minimum Window Subsequence
Master this topic with zero to advance depth.
Minimum Window Subsequence
Given strings s1 and s2, return the minimum contiguous substring part of s1, so that s2 is a subsequence of the part. If there is no such window, return an empty string.
Visual Representation
s1 = "abcdebdde", s2 = "bde"
Forward Pass:
a b c d e b d d e
^ ^ ^
b...d.e (Found at res[1...5])
Backward Pass (Optimization):
From index 4, look for 'e', then 'd', then 'b' backwards.
Found 'b' at index 1 -> Best Window: "bcde"Examples
"bcde" is the smallest substring of s1 where "bde" is a subsequence.
Level I: Brute Force
Intuition
Check every possible substring of s1 and verify if s2 is a subsequence of that substring.
Detailed Dry Run
s1="abcde", s2="bde". Substrings: "a", "ab", "abc", "abcd", "abcde" (Check "abcde": "b","d","e" found! Length 5). Next index...
⚠️ Common Pitfalls & Tips
O(N^2 * M) is extremely slow and will time out.
Level II: Better (Dynamic Programming)
Intuition
We can use DP where dp[i][j] stores the starting index of the shortest substring in s1[0..j] that contains s2[0..i] as a subsequence.
If s1[j] == s2[i], then dp[i][j] = dp[i-1][j-1]. Otherwise, dp[i][j] = dp[i][j-1].
Detailed Dry Run
s1 = 'abcde', s2 = 'bde'. DP table tracks the best starting index for every prefix of s2 found in s1.
⚠️ Common Pitfalls & Tips
Space complexity O(N*M) can be reduced to O(N).
Level III: Optimal (Two Pointers - Two Way Scan)
Intuition
Finding a subsequence window can be done by scanning forward to find any valid window and then scanning backward to minimize the window size from the starting side. This is more efficient than a simple sliding window because subsequence requirements are more flexible than substring requirements.
- Scan s1 forward matching characters of s2 one by one. Once all characters are matched, we have a valid ending index.
- Move backward from the ending index matching characters of s2 in reverse to find the latest possible start index for this specific end index.
- Record the window, shrink the search space, and repeat.
Detailed Dry Run
s1 = 'abcdebdde', s2 = 'bde'.
- Forward: find 'b'(1), 'd'(3), 'e'(4). end=5.
- Backward from index 4: 'e'(4), 'd'(3), 'b'(1). start=1. Window [1, 5)='bcde'.
⚠️ Common Pitfalls & Tips
Ensure the backward pass correctly identifies the latest start index. O(N*M) is the standard solution.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.