Length of smallest substring of a given string which contains another string as 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)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.