Python 3D Academyবাংলা

A window that grows and shrinks: the longest stretch without repeats

🌍 In real life. A hostel canteen writes each day's lunch on a board: biryani, khichuri, fish, biryani, dal, chicken… You want the longest run of days with no dish twice. Walking along the list, you keep a stretch of days in mind. When a dish shows up that is already in your stretch, you drop days from the start of the stretch until the old copy is gone, then carry on. The stretch grows on one end and shrinks on the other, and you never walk backwards.

The idea in one sentence: a window [l, r) whose size changes: grow it on the right one item at a time, and whenever the rule breaks, shrink it from the left until the rule holds again.

Its words:

  • window: the stretch of items between l and r that is being looked at
  • grow: move r right to take in one more item
  • shrink: move l right to drop the leftmost item, until the rule holds again

How it works, step by step (the rule: no letter twice):

  1. keep the letters inside the window in a set
  2. for each new letter at r: while it is already in the set, remove text[l] and move l right
  3. add the new letter; the window text[l:r + 1] has no repeats, so compare its length with the best

Watch the frame stretch and snap shut on "pwwkew":

Why it is correct. The window always has no repeats (we shrink until it doesn't). And no longer answer is skipped: when we move l past a position, every window starting there and reaching r would include both copies of the repeated letter, so none of them could be valid, and the ones ending before r are no longer than a window we already measured.

What it costs, worked out. r moves right n times, and l moves right at most n times in total (it never goes back), so there are at most 2n moves, each an O(1) set operation: O(n). Trying every start and walking until a repeat is up to n²/2 steps: for 10,000 letters, about 50 million against at most 20,000.

def longest_unique(text):
    seen = set()
    l = best = 0
    for r, ch in enumerate(text):
        while ch in seen:          # the rule broke: shrink
            seen.remove(text[l])
            l += 1
        seen.add(ch)               # grow
        best = max(best, r + 1 - l)
    return best

for word in ["pwwkew", "abcabcbb", "bbbb", ""]:
    print(repr(word), longest_unique(word))

Mistakes and edge cases.

  • using if instead of while for the shrink: one step left may not be enough (in "abcb" the repeat is in the middle, not at l)
  • forgetting to remove text[l] from the set before moving l, so the set and the window disagree
  • jumping l back to an earlier position: l must only ever move right
  • an empty text has length 0, and a text of one repeated letter has length 1

Quiz

  1. What is the longest stretch without a repeated letter in "abcabcbb"? What does this print?

    text = "abcabcbb"
    seen, l, best = set(), 0, 0
    for r, ch in enumerate(text):
        while ch in seen:
            seen.remove(text[l])
            l += 1
        seen.add(ch)
        best = max(best, r + 1 - l)
    print(best)
  2. Why is the grow-and-shrink window O(n), even with a loop inside a loop?

    • l only moves right, so the inner loop runs at most n times in total, not n times per letter
    • Sets make every loop O(1)
    • The inner loop never runs
  3. For "abcbd" this answers 4, from the window "bcbd", which repeats b. Which line is wrong?

    def longest_unique(text):
        seen, l, best = set(), 0, 0
        for r, ch in enumerate(text):
            if ch in seen:
                seen.remove(text[l])
                l += 1
            seen.add(ch)
            best = max(best, r + 1 - l)
        return best
  4. What does this print?

    text = "bbbb"
    seen, l, best = set(), 0, 0
    for r, ch in enumerate(text):
        while ch in seen:
            seen.remove(text[l])
            l += 1
        seen.add(ch)
        best = max(best, r + 1 - l)
    print(best, l)

Coding tasks

  1. Write longest_unique(items) in O(n) with a grow-and-shrink window: the length of the longest stretch with no item twice. items can be a string or a list.

  2. Write longest_unique_part(text): the longest stretch of text with no letter twice, as a string (the first one if several are equally long).