LeetCode 727. Minimum Window Subsequence
Question
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:
1 | Input: s1 = "abcdebdde", s2 = "bde" |
Example 2:
1 | Input: s1 = "jmeqksfrsdcmsiwvaovztaqenprpvnbstl", s2 = "u" |
Constraints:
1 <= s1.length <= 2 * 104
1 <= s2.length <= 100
s1
ands2
consist of lowercase English letters.
Source: https://leetcode.com/problems/minimum-window-subsequence/
Solution
A classic sliding window problem. The main idea is to maintain two pointers for two ends of current window. We first move right
forward (expand the window) to find a qualified window, but note that this window may not be the leftmost min window. Then, we move left
forward (shrink the window) to minimize current window.
In this problem, when searching a subsequence, we need to care about both character occurrences and character order. A traditional thought is to maintain thest states so that we are able to know whether the window is still qualified after each shrinking step. However, though occurrences can be recorded easily in a map, it is hard to describe the order of characters. This makes it complex to maintain content states of the window. Thus, we do not maintain the content states of subsequences. Instead, when shrinking the window, we do not scan the window from left to right, but right to left. Actually, it would be more appropriate to say that we find a minimized window in a qualified window from left to right.
Note that the next search after a shrink, should start from one step forward to the old left
. Because only by doing so, we ensure the completeness of the search.
1 | // s1 original string, s2 pattern |
LeetCode 727. Minimum Window Subsequence
http://yenotes.org/2022/03/12/LeetCode-727-Minimum-Window-Subsequence/