A sliding window maintains a contiguous range while moving its left boundary only far enough to restore an invariant.
Python sliding window: longest span without repeated symbols
Operation contract
The scanner finds the length of the longest span with distinct ASCII symbols. Each symbol stores its most recent position. A repeat inside the current window moves the left boundary past that earlier position; a repeat outside it must not move the boundary backward. The program rejects non-ASCII input because this exercise defines symbols as protocol bytes represented in text.
Failure and ownership boundary
This result is a length, not a returned substring. Tie handling would need a separate contract if start and end positions were returned. For Unicode user-visible text, code points do not necessarily correspond to grapheme clusters. Python strings and bytes: reject decoding errors before parsing records and Python prefix-function search: overlapping matches without rescanning use other scanning invariants.
Working program
def distinct_span(sequence):
if not isinstance(sequence, str) or not sequence.isascii() or len(sequence) > 256:
raise ValueError("bounded ASCII sequence required")
left = 0
best = 0
latest = {}
for right, symbol in enumerate(sequence):
left = max(left, latest.get(symbol, -1) + 1)
latest[symbol] = right
best = max(best, right - left + 1)
return best
print(distinct_span("ABCADEAF"))
print(distinct_span(""))
try:
distinct_span("DEL\u00e9")
except ValueError:
print("wire alphabet rejected")Output
5
0
wire alphabet rejectedCosts and limits
For n symbols, expected time is O(n) with suitable dictionary behavior. Stored last positions use O(min(n,128)) entries for this ASCII contract. The max operation prevents a stale repeat from reopening an invalid earlier window.
Common Mistakes
- Never move the left boundary backward after an old repeat.
- A different symbol definition needs different preprocessing.
Connected lessons
Python dictionaries: insertion order and duplicate-key replacement, Python prefix-function search: overlapping matches without rescanning, Python strings and bytes: reject decoding errors before parsing records.
Follow the related contract
Python window exercise: verify a fixed-width maximum against direct slices.
Check the next state boundary
Python longest palindrome: expand around odd and even centers.
Follow the integrity boundary
Python sliding-window maximum: retain only useful deque indexes.
