Spot the bug
This version gives 3 for 'abba' instead of 2. Which line is wrong?
def stretch(s: str) -> int:last: dict[str, int] = {}left = best = 0for right, ch in enumerate(s):if ch in last:left = last[ch] + 1last[ch] = rightbest = max(best, right - left + 1)return bestprint(stretch("abba"))
Choose an answer, then open Show answer below to check it.
Show answer
- Answer: line 5
if ch in last:
Line 5 accepts any earlier sighting, even one before the window. At the final 'a', left jumps back from 2 to 1, so the window wrongly includes two b's. The check must be last.get(ch, -1) >= left.