Minimum Window Subsequence — LeetCode 727 Python Solution

HardLeetCode PremiumStringDynamic ProgrammingSliding Window
Problem
#727
Reading time
3 min

The problem

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 "".

Example

Input
s1 = "abcdebdde", s2 = "bde"
Output
"bcde"
Explanation
"bcde" is the answer because it occurs before "bdde" which has the same length.

Python solution

Python
class Solution:
    def minWindow(self, s1: str, s2: str) -> str:
        m, n = len(s1), len(s2)
        f = [[0] * (n + 1) for _ in range(m + 1)]
        for i, a in enumerate(s1, 1):
            for j, b in enumerate(s2, 1):
                if a == b:
                    f[i][j] = i if j == 1 else f[i - 1][j - 1]
                else:
                    f[i][j] = f[i - 1][j]
        p, k = 0, m + 1
        for i, a in enumerate(s1, 1):
            if a == s2[n - 1] and f[i][n]:
                j = f[i][n] - 1
                if i - j < k:
                    k = i - j
                    p = j
        return "" if k > m else s1[p : p + k]

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 727. Minimum Window Subsequence is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 727. Minimum Window Subsequence?
LeetCode 727. Minimum Window Subsequence is rated Hard on LeetCode.
What is the time complexity of LeetCode 727. Minimum Window Subsequence?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 727. Minimum Window Subsequence?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 727. Minimum Window Subsequence cover?
LeetCode 727. Minimum Window Subsequence is tagged String, Dynamic Programming and Sliding Window on LeetCode.
Is LeetCode 727. Minimum Window Subsequence a premium problem?
Yes. LeetCode 727. Minimum Window Subsequence is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview