Given two strings **A** and **B**, the task is to find the smallest substring of **A** having **B** as a subsequence.

**Examples:**

Input:A = “abcdefababaef”, B = “abf”Output:5Explanation:

Smallest substring of A having B as subsequence is abcdef.

Therefore, the required length is 5.

Input:A = “abcdefababaef”, B = “aef”Output:3

**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[0]**in the string**A**. - After updating the values, remove that character from the Map
**CharacterIndex**. - Otherwise, no further substring is possible.

- If found to be true, then initialize two variables
- 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:

## C++

`// C++ program to implement` `// the above approach` `#include <bits/stdc++.h>` `using` `namespace` `std;` `// Function to find the length of` `// smallest substring of a having` `// string b as a subsequence` `int` `minLength(string a, string b)` `{` ` ` `// Stores the characters present` ` ` `// in string b` ` ` `map<` `char` `, ` `int` `> Char;` ` ` `for` `(` `int` `i = 0; i < b.length(); i++) {` ` ` `Char[b[i]]++;` ` ` `}` ` ` `// Find index of characters of a` ` ` `// that are also present in string b` ` ` `map<` `char` `, vector<` `int` `> > CharacterIndex;` ` ` `for` `(` `int` `i = 0; i < a.length(); i++) {` ` ` `char` `x = a[i];` ` ` `// If character is present in string b` ` ` `if` `(Char.find(x) != Char.end()) {` ` ` `// Store the index of character` ` ` `CharacterIndex[x].push_back(i);` ` ` `}` ` ` `}` ` ` `int` `len = INT_MAX;` ` ` `// Flag is used to check if` ` ` `// substring is possible` ` ` `int` `flag;` ` ` `while` `(` `true` `) {` ` ` `// Assume that substring is` ` ` `// possible` ` ` `flag = 1;` ` ` `// Stores first and last` ` ` `// indices of the substring` ` ` `// respectively` ` ` `int` `firstVar, lastVar;` ` ` `for` `(` `int` `i = 0; i < b.length(); i++) {` ` ` `// For first character of string b` ` ` `if` `(i == 0) {` ` ` `// If the first character of` ` ` `// b is not present in a` ` ` `if` `(CharacterIndex.find(b[i])` ` ` `== CharacterIndex.end()) {` ` ` `flag = 0;` ` ` `break` `;` ` ` `}` ` ` `// If the first character of b` ` ` `// is present in a` ` ` `else` `{` ` ` `int` `x = *(` ` ` `CharacterIndex[b[i]].begin());` ` ` `// Remove the index from map` ` ` `CharacterIndex[b[i]].erase(` ` ` `CharacterIndex[b[i]].begin());` ` ` `// Update indices of` ` ` `// the substring` ` ` `firstVar = x;` ` ` `lastVar = x;` ` ` `}` ` ` `}` ` ` `// For the remaining characters of b` ` ` `else` `{` ` ` `int` `elementFound = 0;` ` ` `for` `(` `auto` `e : CharacterIndex[b[i]]) {` ` ` `if` `(e > lastVar) {` ` ` `// If index possible for` ` ` `// current character` ` ` `elementFound = 1;` ` ` `lastVar = e;` ` ` `break` `;` ` ` `}` ` ` `}` ` ` `if` `(elementFound == 0) {` ` ` `// If no index is possible` ` ` `flag = 0;` ` ` `break` `;` ` ` `}` ` ` `}` ` ` `}` ` ` `if` `(flag == 0) {` ` ` `// If no more substring` ` ` `// is possible` ` ` `break` `;` ` ` `}` ` ` `// Update the minimum length` ` ` `// of substring` ` ` `len = min(len,` ` ` `abs` `(lastVar - firstVar) + 1);` ` ` `}` ` ` `// Return the result` ` ` `return` `len;` `}` `// Driver Code` `int` `main()` `{` ` ` `// Given two string` ` ` `string a = ` `"abcdefababaef"` `;` ` ` `string b = ` `"abf"` `;` ` ` `int` `len = minLength(a, b);` ` ` `if` `(len != INT_MAX) {` ` ` `cout << len << endl;` ` ` `}` ` ` `else` `{` ` ` `cout << ` `"Impossible"` `<< endl;` ` ` `}` `}` |

*chevron_right*

*filter_none*

## Python3

`# Python3 program to implement` `# the above approach` `import` `sys` `# Function to find the length of` `# smallest substring of a having` `# string b as a subsequence` `def` `minLength(a, b):` ` ` ` ` `# Stores the characters present` ` ` `# in string b` ` ` `Char ` `=` `{}` ` ` `for` `i ` `in` `range` `(` `len` `(b)):` ` ` `Char[b[i]] ` `=` `Char.get(b[i], ` `0` `) ` `+` `1` ` ` `# Find index of characters of a` ` ` `# that are also present in string b` ` ` `CharacterIndex ` `=` `{}` ` ` `for` `i ` `in` `range` `(` `len` `(a)):` ` ` `x ` `=` `a[i]` ` ` `# If character is present in string b` ` ` `if` `(x ` `in` `Char):` ` ` ` ` `# Store the index of character` ` ` `CharacterIndex[x] ` `=` `CharacterIndex.get(x, [])` ` ` `CharacterIndex[x].append(i)` ` ` `l ` `=` `sys.maxsize` ` ` `# Flag is used to check if` ` ` `# substring is possible` ` ` `while` `(` `True` `):` ` ` ` ` `# Assume that substring is` ` ` `# possible` ` ` `flag ` `=` `1` ` ` `firstVar ` `=` `0` ` ` `lastVar ` `=` `0` ` ` ` ` `# Stores first and last` ` ` `# indices of the substring` ` ` `# respectively` ` ` `for` `i ` `in` `range` `(` `len` `(b)):` ` ` ` ` `# For first character of string b` ` ` `if` `(i ` `=` `=` `0` `):` ` ` ` ` `# If the first character of` ` ` `# b is not present in a` ` ` `if` `(b[i] ` `not` `in` `CharacterIndex):` ` ` `flag ` `=` `0` ` ` `break` ` ` `# If the first character of b` ` ` `# is present in a` ` ` `else` `:` ` ` `x ` `=` `CharacterIndex[b[i]][` `0` `]` ` ` `# Remove the index from map` ` ` `CharacterIndex[b[i]].remove(` ` ` `CharacterIndex[b[i]][` `0` `])` ` ` `# Update indices of` ` ` `# the substring` ` ` `firstVar ` `=` `x` ` ` `lastVar ` `=` `x` ` ` `# For the remaining characters of b` ` ` `else` `:` ` ` `elementFound ` `=` `0` ` ` `for` `e ` `in` `CharacterIndex[b[i]]:` ` ` `if` `(e > lastVar):` ` ` ` ` `# If index possible for` ` ` `# current character` ` ` `elementFound ` `=` `1` ` ` `lastVar ` `=` `e` ` ` `break` ` ` ` ` `if` `(elementFound ` `=` `=` `0` `):` ` ` ` ` `# If no index is possible` ` ` `flag ` `=` `0` ` ` `break` ` ` ` ` `if` `(flag ` `=` `=` `0` `):` ` ` ` ` `# If no more substring` ` ` `# is possible` ` ` `break` ` ` `# Update the minimum length` ` ` `# of substring` ` ` `l ` `=` `min` `(l, ` `abs` `(lastVar ` `-` `firstVar) ` `+` `1` `)` ` ` `# Return the result` ` ` `return` `l` `# Driver Code` `if` `__name__ ` `=` `=` `'__main__'` `:` ` ` ` ` `# Given two string` ` ` `a ` `=` `"abcdefababaef"` ` ` `b ` `=` `"abf"` ` ` `l ` `=` `minLength(a, b)` ` ` `if` `(l !` `=` `sys.maxsize):` ` ` `print` `(l)` ` ` `else` `:` ` ` `print` `(` `"Impossible"` `)` ` ` `# This code is contributed by SURENDRA_GANGWAR` |

*chevron_right*

*filter_none*

**Output:**

5

**Time Complexity:** O(N^{2})**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.

## Recommended Posts:

- Find length of longest subsequence of one string which is substring of another string
- Length of the smallest substring which contains all vowels
- Minimize elements to be added to a given array such that it contains another given array as its subsequence
- Minimize elements to be added to a given array such that it contains another given array as its subsequence | Set 2
- Length of the largest substring which have character with frequency greater than or equal to half of the substring
- Lexicographically smallest permutation of a string that contains all substrings of another string
- Lexicographically smallest and largest anagrams of a string containing another string as its substring
- Length of longest substring to be deleted to make a string equal to another string
- Smallest string which not a subsequence of the given string
- Lexicographically smallest permutation of a string that can be reduced to length K by removing K-length prefixes from palindromic substrings of length 2K
- Minimum K such that every substring of length atleast K contains a character c
- Maximum length prefix of one string that occurs as subsequence in another
- Minimum length of substring whose rotation generates a palindromic substring
- Check if the given string is shuffled substring of another string
- Check if a String contains Anagrams of length K which does not contain the character X
- Minimum substring flips required to convert given binary string to another
- Smallest non-zero substring which has any permutation divisible by 2^K
- Find if a given string can be represented from a substring by iterating the substring ānā times
- Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'th substring
- Construct a string of length L such that each substring of length X has exactly Y distinct letters

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.