150 XP

97. Smallest window with every letter

Expert sliding window dictionaries

Write a function smallest_window(text, letters) that returns the shortest stretch of text (characters next to each other) that contains every character of letters:

  • Counts matter: if letters has a character twice, the stretch needs it at least twice. "aa" is not found in "ab".
  • The stretch may hold other characters too, and the order doesn't matter.
  • Capitals and lower case are different characters.
  • If several stretches are equally short, return the one that starts first. If there is none, return "".

Checking every stretch is far too slow for long texts. A window can slide along instead: it grows to the right until it holds everything, then shrinks from the left for as long as it still does, and each character goes in and out of it only once.

Example 1

Inputtext = "xaybzcyab", letters = "abc"
Output"cyab"
Explanation"aybzc" also has them; "cyab" is shorter.

Example 2

Inputtext = "baab", letters = "aa"
Output"aa"
ExplanationBoth a's are needed.

Example 3

Inputtext = "abc", letters = "d"
Output""
ExplanationNo d anywhere.

Constraints

  • text has 0 to 1000 and letters 1 to 50 characters, letters of either case.

Submit also runs 11 more tests you can't see.

Code
def smallest_window(text, letters):
    """Find the shortest stretch holding all the letters.

    text: str, the text to search; may be empty
    letters: str, the characters needed (with repeats)
    Returns: str, the shortest such stretch (the first, on
        a tie), or "" if there is none
    """
    # Write your code here
    pass