Given two strings string1 and string2, find the smallest substring in string1 containing all characters of string2 efficiently.
Input : string = "this is a test string" pattern = "tist" Output : Minimum window is "t stri" Explanation: "t stri" contains all the characters of pattern. Input : string = "geeksforgeeks" pattern = "ork" Output : Minimum window is "ksfor"
Method 1 ( Brute force solution )
1- Generate all substrings of string1 (“this is a test string”)
2- For each substring, check whether the substring contains all characters of string2 (“tist”)
3- Finally, print the smallest substring containing all characters of string2.
Method 2 ( Efficient Solution )
1- First check if length of string is less than the length of given pattern, if yes then "no such window can exist ". 2- Store the occurrence of characters of given pattern in a hash_pat. 3- Start matching the characters of pattern with the characters of string i.e. increment count if a character matches 4- Check if (count == length of pattern ) this means a window is found 5- If such window found, try to minimize it by removing extra characters from beginning of current window. 6- Update min_length. 7- Print the minimum length window.
Diagram to explain above algorithm:
Below is program to implement above algorithm
Smallest window is : t stri
This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Smallest window that contains all characters of string itself
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Program to find the largest and smallest ASCII valued characters in a string
- Length of the smallest sub-string consisting of maximum distinct characters
- Minimal moves to form a string by adding characters or appending string itself
- Create a new string by alternately combining the characters of two halves of the string in reverse
- Minimum deletions from string to reduce it to string with at most 2 unique characters
- Find the player who rearranges the characters to get a palindrome string first
- Python Dictionary to find mirror characters in a string
- Find the longest substring with k unique characters in a given string
- Find largest word in dictionary by deleting some characters of given string
- Program to find the product of ASCII values of characters in a string
- Lexicographically smallest string whose hamming distance from given string is exactly K
- String matching where one string contains wildcard characters
- Remove characters from the first string which are present in the second string