Length of smallest substring of a given string which contains another string as subsequence | Set 2
Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence.
Input: A = “abcdefababaef”, B = “abf”
Smallest substring of A having B as subsequence is abcdef.
Therefore, the required length is 5.
Input: A = “abcdefababaef”, B = “aef”
Approach: Follow the steps below to solve the problem:
- Store all the indices of the characters of A which are also present in B in a Map CharacterIndex.
- Traverse over all the characters of string B.
- Check if the first character of string B is present in the string A or not:
- If found to be true, then initialize two variables firstVar and lastVar with the index of the first occurrence of B in the string A.
- After updating the values, remove that character from the Map CharacterIndex.
- Otherwise, no further substring is possible.
- For the remaining characters of B, check if the character is present in the string A or not. If found to be true, traverse through all the occurrences of that character in the string A and if the index of that character in the string A exceeds lastVar, then update the lastVar with that index. Otherwise, no further substring is possible.
- If B is completely traversed, update answer with the difference between firstVar and the lastVar.
- Print the final minimized answer.
Below is the implementation of the above approach:
Time Complexity: O(N2)
Auxiliary Space: O(N), since N extra space has been taken.
My Personal Notes arrow_drop_up
Please Login to comment...