VOOZH about

URL: https://www.geeksforgeeks.org/python/python-get-the-smallest-window-in-a-string-containing-all-characters-of-given-pattern/

⇱ Get the Smallest Window in a String Containing all Characters of Given Pattern - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Get the Smallest Window in a String Containing all Characters of Given Pattern - Python

Last Updated : 11 Jul, 2025

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

Sliding Window with defaultdict()

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.


Output
geeks

Explanation:

  • window expands by increasing j updating the character counts in src (a dictionary).
  • when all characters in p are present with required frequencies in src, a valid window is found.
  • window is shrunk by moving the left boundary (i) forward, reducing counts in src then the smallest valid window is stored and returned.

Dynamic Last-Occurrence Update

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.


Output
geeks

Explanation:

  • last_occ tracks the last index of characters in p found in s.
  • when all characters from p are found then the leftmost and rightmost indices are used to form a window.
  • smallest window is compared and updated if necessary and the final smallest window is returned.

Using enumerate()

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.


Output
ring

Explanation:

  • enumerate(s) identifies indices of characters in p found in s and the leftmost and rightmost indices from indices form the window.
  • substring between those indices is returned as the result.
  • If no indices are found then an empty string is returned.
Comment
Article Tags: