![]() |
VOOZH | about |
Given two strings s1 and s2, find the smallest contiguous substring of s1 in which s2 appears as a subsequence.
Examples:
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.Input: s1 = "abcdebdde", s2 = "bde"
Output: "bcde"
Explanation: "bcde" and "bdde" are two substring of s1 where s2 occurs as subsequence but "bcde" occur first so we return that.Input: s1 = "ad", s2 = "b"
Output: ""
Explanation: There is no substring exists.
Table of Content
The idea is to iterate through all possible substrings of s1 and check each one to see if s2 appears as a subsequence within it. We keep track of the shortest substring that meets this condition, updating whenever we find a smaller one.
If multiple substrings have the same length, the first occurring one is selected. If no substring contains s2 as a subsequence, we return an empty string.
bcde
The idea is to iterate through s1 and, for each position where the first character of s2 matches, move forward with two pointers to find the complete subsequence s2.
Once matched, backtrack from the end position to shrink the window to the smallest substring that still contains s2 as a subsequence.
Track the minimum-length substring found and update it whenever a smaller one is discovered.
If no match is found, return an empty string.
bcde
The idea is to preprocess s1 so we can quickly jump to the next occurrence of any character, instead of scanning it repeatedly.
We create a nextPos table where nextPos[i][ch] stores the index of the next occurrence of character ch after position i in s1. This table is filled by traversing s1 from right to left.
Then, for each possible starting position in s1 that matches the first character of s2, we try to match all characters of s2 by repeatedly jumping through the nextPos table.
If we successfully match all of s2, we track the minimal window length and update the answer.
Step by Step Approach:
bcde