11. Minimum Window Subsequence
β GFG solution to the Minimum Window Subsequence problem: find the smallest substring in s1 that contains s2 as a subsequence using greedy backtracking and two-pointer techniques. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given two strings, s1 and s2. Your task is to find the smallest substring in s1 such that s2 appears as a subsequence within that substring.
The characters of
s2must appear in the same sequence within the substring ofs1.If there are multiple valid substrings of the same minimum length, return the one that appears first in
s1.If no such substring exists, return an empty string.
Note: Both the strings contain only lowercase English letters.
π Examples
Example 1
Input: s1 = "geeksforgeeks", s2 = "eksrg"
Output: "eksforg"
Explanation: "eksforg" satisfies all required conditions. s2 is its subsequence and it is
smallest and leftmost among all possible valid substrings of s1.Example 2
Input: s1 = "abcdebdde", s2 = "bde"
Output: "bcde"
Explanation: "bcde" and "bdde" are two substrings of s1 where s2 occurs as subsequence
but "bcde" occurs first so we return that.Example 3
π Constraints
$1 \le \text{s1.length} \le 10^4$
$1 \le \text{s2.length} \le 50$
β
My Approach
The optimal approach uses a Greedy Backtracking with Two-Pointer technique to efficiently find the minimum window subsequence:
Greedy Backtracking Strategy
Forward Pass - Find Complete Subsequence:
Use two pointers:
ifors1andjfors2.Move
iforward throughs1, incrementingjwhenever characters match.When
jreaches the end ofs2, we've found a valid window endpoint.
Backward Pass - Minimize Window:
Once a complete subsequence is found, backtrack from the current position.
Move
ibackward while decrementingjto find the leftmost starting position.This gives us the minimum window for this particular endpoint.
Track Minimum Window:
Compare the current window length with the global minimum.
Update the result if a smaller window is found.
Continue the forward pass to explore other potential windows.
Optimization:
After each backtrack, resume the forward search from the optimized starting position.
This ensures we don't miss any potentially smaller windows.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(m Γ n), where m is the length of
s1and n is the length ofs2. In the worst case, for each character ins1, we might backtrack through the entire subsequences2.Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for pointers and variables, regardless of the input size.
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated