Python | Get the smallest window in a string containing all characters of given pattern
Given two strings str and pattern, find the smallest substring in str containing all characters of pattern efficiently. Examples:
Input : str = 'geeksforgeeks' pattern = 'gks' Output : geeks Input : str = 'new string' pattern = 'rg' Output : ring
Approach #1 : Using Python enumerate() This method uses Python enumerate(). need[k] store how many times we need character k and missing tells how many characters are still missing. In the loop, first add the new character to the window. Then, if nothing is missing, remove as much as possible from the window start and then update the result.
Approach #2 : Using collections.defaultdict() This method make use of two defaultdicts ‘src’ and ‘dest’. A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments. source is empty while target consist of pattern elements as keys and the count of occurrence as value. In every iteration ‘i’, we check if the ith element of str is present in target dictionary or not and update source dictionary accordingly.
Approach #3 : Dynamic approach In this method, we use a for loop and in every iteration, say i, we find the shortest interval that ends in i and includes all letters in the pattern. This can be done by taking two data structures in account i.e. ‘rpos’ and ‘rdict’. rpos is a sorted list of positions where rightmost positions of characters of pattern in str are kept and rdict is a dictionary mapping from a character to the position. values of rdict is same as rpos.
Method#4: Using brute force
Iterate through all possible starting and ending indices of the window, check if the current window contains all characters of the pattern, and update the smallest window and smallest substring if the current window is smaller than the previous smallest window. Return the smallest substring.
1. Initialize the smallest window to be the length of the string and the smallest substring to be an empty string.
2. Iterate through all possible starting indices of the window, i.e., from 0 to (len(string)-len(pattern)).
3. For each starting index, iterate through all possible ending indices of the window, i.e., from (starting index + len(pattern)) to len(string).
4. Check if the current window contains all characters of the pattern.
5. If it does, update the smallest window and smallest substring if the current window is smaller than the previous smallest window.
6. Return the smallest substring.
Time Complexity: O(n^3) – where n is the length of the string. This is because we have three nested loops.
Space Complexity: O(1) – constant space is used.
Please Login to comment...