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.
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
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.