97. Smallest window with every letter
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
lettershas 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
text = "xaybzcyab", letters = "abc""cyab"Example 2
text = "baab", letters = "aa""aa"Example 3
text = "abc", letters = "d"""Constraints
texthas 0 to 1000 andletters1 to 50 characters, letters of either case.
Submit also runs 11 more tests you can't see.
- Count what is still needed:
need = collections.Counter(letters), andmissing = len(letters), the number of characters still missing from the window. - Move the right edge one character at a time. If that character was still needed (
need[ch] > 0), one fewer is missing. Either way,need[ch] -= 1: a count below 0 means the window has spares. - While nothing is missing, the window is a candidate: keep it if it is shorter than the best (strictly, so the first one wins a tie), then drop the left character, giving it back to
need, and move the left edge on.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.