Problem Description
Given two strings s1 and s2, the goal is to find the minimum contiguous substring of s1 such that s2 is a subsequence of that substring. In other words, all characters of s2 must appear in the substring in the same order, although not necessarily consecutively. If there is no such substring in s1, return an empty string. If more than one valid substring exists with the same minimal length, return the one that starts earliest in s1.
Key Insights
- The problem is different from the classic "minimum window substring" because the characters of s2 must appear in order.
- A two-pointer approach can be used to first "fast-forward" to find a valid window end where the last character of s2 is matched.
- Once the end is found, a reverse scan is applied to find the beginning of the window by matching s2 in reverse order.
- Updating the result when a smaller window is found is crucial.
- The approach runs in O(n * m) time, with n and m being the lengths of s1 and s2 respectively.
Space and Time Complexity
Time Complexity: O(n * m), where n is the length of s1 and m is the length of s2. Space Complexity: O(1) additional space is used apart from the input strings.
Solution
The solution uses a two-phase approach for each candidate window:
- Use a forward pointer to traverse s1 until we find a valid window ending at an index where the last character of s2 is matched.
- Once a valid end is detected, use a backward pointer starting at that index and move in reverse to find the start index of the window where s2 fully matches as a subsequence.
The algorithm repeatedly checks every possible window end where the match is complete and updates the minimal window to return the left-most minimal substring if multiple windows of the same length exist.