Minimum Window Subsequence Problem
Description
LeetCode Problem 727.
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 in s1 that covers all characters in s2, return the empty string "". If there are multiple such minimum-length windows, return the one with the left-most starting index.
Example 1:
Input: s1 = "abcdebdde", s2 = "bde"
Output: "bcde"
Explanation:
"bcde" is the answer because it occurs before "bdde" which has the same length.
"deb" is not a smaller window because the elements of s2 in the window must occur in order.
Example 2:
Input: s1 = "jmeqksfrsdcmsiwvaovztaqenprpvnbstl", s2 = "u"
Output: ""
Constraints:
1 <= s1.length <= 2 * 10^41 <= s2.length <= 100s1ands2consist of lowercase English letters.
Solution
Approach: Dynamic Programming over Window Starts
For a window that ends at index i of s1, the shortest one is the one that starts as late as possible. So we track, for each prefix of s2, the latest possible start.
Let start[j] be the latest index p such that s2[0..j) is a subsequence of s1[p..i], or -1 if there is none. When we move to the next character c = s1[i]:
- If
c == s2[j - 1],ccan be the match for thej-th character ofs2. Forj = 1the window starts right here, sostart[1] = i. Forj > 1the firstj - 1characters must be matched beforei, sostart[j]takes the old value ofstart[j - 1]. - Otherwise
start[j]keeps its value: the same window just grows by one character.
Go through j from len(s2) down to 1. That way start[j - 1] still holds its value from before index i, and one character of s1 is never used for two characters of s2.
After each index, if start[n] != -1, the window s1[start[n]..i] contains all of s2 in order. Keep it if it is strictly shorter than the best so far. On a tie, the window found earlier also starts earlier, so it wins, as the problem asks.
Complexity: O(m · n) time, where m and n are the lengths of s1 and s2, and O(n) extra space.
class Solution:
def minWindow(self, s1: str, s2: str) -> str:
n = len(s2)
# start[j] = the latest start of a window of s1 that ends at the current index
# and contains s2[:j] as a subsequence (-1 if there is none).
start = [-1] * (n + 1)
best_start, best_len = -1, len(s1) + 1
for i, c in enumerate(s1):
# Go down so start[j - 1] still holds its value from before index i.
for j in range(n, 0, -1):
if c == s2[j - 1]:
start[j] = i if j == 1 else start[j - 1]
# Strictly shorter only: on a tie the earlier window wins.
if start[n] != -1 and i - start[n] + 1 < best_len:
best_start, best_len = start[n], i - start[n] + 1
return "" if best_start == -1 else s1[best_start:best_start + best_len]