Sliding window
Скользящее окно
This technique moves a range over consecutive elements in a sequence. As elements enter or leave the range, the algorithm updates what it knows about the range instead of starting over.
What the window represents
A window is a contiguous range in a sequence. On a list of temperatures, a seven-day window contains seven consecutive readings. Move it forward one day and six readings stay the same. To calculate the next average, you can update the running sum by subtracting the oldest reading and adding the newest, then divide by seven.
Fixed and variable windows
A fixed-size window moves both boundaries together. Use it when the problem gives you a length: for example, find the highest total over any three consecutive days. The state you maintain depends on the question. A sum needs one running total, but a maximum cannot generally be updated from the old maximum alone: if that value leaves, you need to know what replaces it. A monotonic deque can keep track of the remaining candidates.
A variable-size window moves the boundaries independently. To find the longest substring with at most k distinct characters, extend the right boundary one character at a time and maintain a frequency table. While the table has more than k distinct characters, move the left boundary forward, deleting any entry whose count drops to zero. Once the window is valid again, compare its length with the best so far.
Example: highest total over k consecutive readings
def best_total(readings, k):
if not 1 <= k <= len(readings):
raise ValueError('invalid window size')
total = sum(readings[i] for i in range(k))
best = total
for i in range(k, len(readings)):
total += readings[i] - readings[i - k]
best = max(best, total)
return best
For [4, -2, 6, 1] with k = 2, the totals are 2, 4, and 7. Building the first window costs O(k) time, and each of the remaining n - k moves costs O(1). That gives O(n) time and O(1) extra space for an indexable input like a list. For a stream, the same update needs access to the outgoing reading, so you'd typically keep the last k readings in a queue.
What interviewers look for
Explain both what your state represents and why moving a boundary won't discard a possible answer. In the distinct-character example, extending a window that already contains too many distinct characters cannot make it valid, so it's safe to rule out its current starting position. Don't assume every condition behaves this way: if negative numbers are allowed, adding an element can make an over-budget sum valid again.
A nested shrinking loop doesn't automatically make the solution quadratic. Count how many times each boundary moves across the entire run: if neither moves backward, each advances at most n times. With constant-time state updates, that gives linear time. For index-based code, test k = 1 and k = n to catch boundary errors.