Find the smallest window in a string containing all characters of another string
- Difficulty Level : Hard
- Last Updated : 22 Jun, 2022
Given two strings, string1 and string2, the task is to 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 )
- First check if the length of the string is less than the length of the given pattern, if yes then “no such window can exist “.
- Store the occurrence of characters of the given pattern in a hash_pat.
- we will be using two pointer technique basically
- Start matching the characters of pattern with the characters of string i.e. increment count if a character matches.
- Check if (count == length of pattern ) this means a window is found.
- If such a window found, try to minimize it by removing extra characters from the beginning of the current window.
- delete one character from first and again find this deleted key at right, once found apply step 5 .
- Update min_length.
- Print the minimum length window.
A diagram to explain the stated algorithm:
Below is the program to implement the above algorithm:
Smallest window is : t stri
Time Complexity : O(n) , where n is the length of string str.
Method 3 (Efficient Solution)
(Using sliding window Technique )
-->Smallest window that contain all character : BANC
Time Complexity : O(|s|) , where |s| is the length of string s.
Space Complexity : O(1)
Explanation – Array m of length 256 is used ,which is constant space, so the Space Complexity is O(1).
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. 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.