If these ideas are new, begin with:
Understand the idea
Variable windows expand right, then move left until a validity rule is restored. For longest valid intervals, shrinking should discard only starts that cannot be used at the current right boundary.
Work through an example
'abca' reaches a duplicate a. Remove the leftmost a and keep 'bca', length 3. In 'abba', remove a then b to restore uniqueness.
Time and space complexity
O(n) boundary movements, expected O(n) hash work, O(σ) live character state.
Why it works
After shrinking, the current interval is valid and all earlier starts at this right were invalid.
Common mistakes
- Using if instead of while may leave multiple violations.
- Update best after restoring validity.
Chapter lab · Python implementation
A window represents a contiguous active interval. Reuse its overlapping state when advancing boundaries. The lab finds the longest substring with distinct characters; a fixed-size sum example contrasts automatic eviction with condition-based shrinking. Bounds below count code points, not user-visible grapheme clusters.
This shared lab connects the chapter's topics. Follow the current lesson's worked example first, then trace the complete implementation. Additional algorithms described in topic exercises are variations you can implement independently.
def max_window_sum(values,k):
if not 1<=k<=len(values):
raise ValueError('invalid k')
current=0
for i in range(k):
current+=values[i]
best=current
for right in range(k,len(values)):
current+=values[right]-values[right-k]
best=max(best,current)
return best
def longest_unique(text):
counts={}
left=best=0
for right,char in enumerate(text):
counts[char]=counts.get(char,0)+1
while counts[char]>1:
old=text[left]
counts[old]-=1
if counts[old]==0:
del counts[old]
left+=1
best=max(best,right-left+1)
return bestRun and test the lab
Copy the implementation and these assertions into a Python 3 file and run it. An assertion failure means the actual result differs from the expectation. Add the current topic's exercise and boundary tests to deepen your understanding.
assert max_window_sum([2,1,5,1,3,2],3)==9
assert max_window_sum([-5,-2,-8],2)==-7
assert longest_unique('abca')==3
assert longest_unique('')==0
assert longest_unique('abba')==2