![]() |
VOOZH | about |
Our task is to find the smallest substring in a given string that contains all the characters of a given pattern. In other words, we are given two strings: one is the main string and the other is the pattern. We need to locate the smallest window in the main string which includes every character from the pattern. For example, consider: s = "geeksforgeeks" and p = "gks" here the smallest substring in s that contains all characters from p is "geeks".
This method uses a sliding window to expand and contract while tracking character frequencies with a defaultdict(). The window expands until it satisfies the required character counts from the pattern then contracts to find the smallest valid window.
geeks
Explanation:
This approach dynamically updates the last seen indices for each required character as we traverse the string and when all required characters have been encountered, the window is defined from the minimum to the maximum index among these characters.
geeks
Explanation:
This simple method uses enumerate() to collect all indices of characters in the main string that are in the pattern then extracts the substring spanning from the minimum to maximum index.
ring
Explanation: