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.
string = 'new string'pattern = 'rg' # let's find the index of r and g in String and the # stor them in index list (index[]) index=[] for x in range(len(pattern)): if pattern[x] in string: index.append(string.index(pattern[x])) # sorting the r and g index's index.sort() # save first index in l l = len(index) low = int(index[0]) # save last index in h high = int(index[l-1]) h = high +1for i in range(low,h): print(string[i],end=" ") |
ksf
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.
# Python3 code to Find the smallest # window in a string containing all # characters of another string from collections import defaultdict import sys def min_window(str, pattern): # Function to check validity of source and # destination def isValid(i, j): for item in j: if item not in i or i[item] < j[item]: return False return True source = defaultdict(int) target = defaultdict(int) # Target consist pattern elements and 1 # as key:value pair for e in pattern: target[e] += 1 # Minimum length for window minLen = sys.maxsize n = len(str) ans, j = '', 0 for i in range(n): # Update source for valid source - target pair while j < n and (isValid(source, target) == False): source[str[j]] += 1 j += 1 # Checking validity of source-target pair if isValid(source, target): if minLen > j-i + 1: minLen = j-i + 1 ans = str[i:j] source[str[i]] -= 1 return ans # Driver Code string = "geekforgeeks"pattern = "gks"print(min_window(string, pattern)) |
geeks
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.
# Python3 code to Find the smallest # window in a string containing all # characters of another string from collections import Counter, defaultdict def min_window(str, pattern): rdict, count = defaultdict(list), Counter(pattern) rpos, res = [], "" # Loop only over c exist in pattern for i, c in filter(lambda x: x[1] in pattern, enumerate(str)): if len(rdict) == count: # If reached limit, remove rpos.remove(rdict.pop(0)) # Add to dict rdict[i].append(i) # Add to list rpos.append(i) if (len(rpos) == len(pattern) and (res =="" or rpos[-1]-rpos[0]<len(res))): res = str[rpos[0]:rpos[-1]+1] return res # Driver Code string = "geeksforgeeks"pattern = "gks"print(min_window(string, pattern)) |
geeks
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 the smallest window in a string containing all characters of another string
- Smallest window that contains all characters of string itself
- Minimize length of prefix of string S containing all characters of another string T
- Swap all occurrences of two characters to get lexicographically smallest string
- Lexicographic smallest permutation of a String containing the second String as a Substring
- Lexicographically smallest and largest anagrams of a string containing another string as its substring
- Print list items containing all characters of a given word
- Smallest number containing all possible N length permutations using digits 0 to D
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Shortest substring of a string containing all given words
- String containing first letter of every word in a given string with spaces
- Python - Remove words containing list characters
- Python - Get the indices of Uppercase characters in given string
- Minimum number of operations to move all uppercase characters before all lower case characters
- Min flips of continuous characters to make all characters same in a string
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Python | Remove List elements containing given String character
- Lexicographically smallest substring with maximum occurrences containing a's and b's only
- Lexicographically smallest K-length substring containing maximum number of vowels
- Program to print window pattern
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.
Improved By : Prakash Singh 6

