Minimum Window Subsequence - Problem

Given two strings s1 and s2, return the minimum contiguous substring of s1 such that s2 is a subsequence of this substring.

If no such window exists in s1 that covers all characters of s2, return an empty string "".

If there are multiple such minimum-length windows, return the one with the leftmost starting index.

Note: A subsequence is a sequence that can be derived from another sequence by deleting some (not necessarily consecutive) elements without changing the order of the remaining elements.

Input & Output

Example 1 — Basic Case
$ Input: s1 = "adbec", s2 = "abc"
Output: "adbec"
💡 Note: The minimum window substring "adbec" contains "abc" as a subsequence: a→d→b→e→c matches a→b→c by taking positions 0, 2, 4.
Example 2 — No Valid Window
$ Input: s1 = "adc", s2 = "abc"
Output: ""
💡 Note: There is no subsequence "abc" in "adc" because 'b' is missing, so return empty string.
Example 3 — Multiple Windows
$ Input: s1 = "abacbcab", s2 = "abc"
Output: "abc"
💡 Note: Multiple valid windows exist: "abacbc" and "abc". We return "abc" as it's shorter and leftmost among equal-length options.

Constraints

  • 1 ≤ s1.length ≤ 2000
  • 1 ≤ s2.length ≤ 100
  • s1 and s2 consist of lowercase English letters only

Visualization

Tap to expand
Minimum Window Subsequence INPUT s1 = "adbec" a 0 d 1 b 2 e 3 c 4 s2 = "abc" a b c Find smallest substring of s1 containing s2 as a subsequence s1 = "adbec" s2 = "abc" ALGORITHM STEPS 1 Forward Pass Find end of window by matching s2 in s1 2 Backward Pass Go back to find start of minimal window 3 Update Minimum Track shortest window found so far 4 Continue Search Move start+1, repeat until end of s1 Matching Process: s1: a d b e c ^ ^ ^ s2: a b c Window: [0,4] len=5 FINAL RESULT Minimum Window Found: "adbec" Window indices: [0, 4] Length: 5 Verification: a d b e c Green = matched chars Output: "adbec" Key Insight: The two-pointer approach with forward-backward passes achieves O(n*m) time complexity. Forward pass finds a valid window end, backward pass minimizes window start. This ensures we find the smallest window containing s2 as a subsequence with leftmost starting index. TutorialsPoint - Minimum Window Subsequence | Optimal Solution Time: O(n * m) | Space: O(1)
Asked in
Google 25 Facebook 20 Amazon 15 Microsoft 12
28.5K Views
Medium Frequency
~35 min Avg. Time
865 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen