Sliding Window
Loading
Loading
Sliding Window
Grow on the right, shrink from the left, and never move an edge backwards.
By the end of this chapter
def longest_valid(items): left = 0 best = 0 state = {} for right, value in enumerate(items): add(state, value) # 'while', not 'if': one arrival can force several departures. while not is_valid(state): remove(state, items[left]) left += 1 best = max(best, right - left + 1) return bestConcept
The nested loop looks quadratic, but the left edge only ever moves forward and can never pass the right edge. Across the whole run it advances at most n times in total, so the two loops together do O(n) work.
The window is only as fast as its validity test. Comparing two frequency maps every iteration is O(alphabet) per step and quietly ruins the complexity. Maintain a scalar instead.
# Instead of comparing maps, count how many requirements are fully met.if window[char] == need[char]: satisfied += 1 # only at the exact crossing point...if window[char] < need[char]: satisfied -= 1 # only when it drops belowCan you recognise the pattern?
A question about the longest, shortest, or number of contiguous ranges meeting a condition.
Quick quiz
Sign in to keep a note here. It is free, and nobody else can see it.
Sign inWhat this chapter was for:
Before moving on: take the quiz above, and try 3 practice problems.