Algorithmic patterns · 1 / 15 Theory

Sliding window

Many problems ask something about consecutive stretches of a list or string: the largest sum of 3 consecutive items, the longest substring without repeats… The naive solution looks at each stretch from scratch (O(n·k) or worse). A sliding window keeps the current stretch and updates it as it moves: each element enters and leaves once, O(n).

Fixed-size window

def max_sum(numbers, k):
    window = sum(numbers[:k])               # first window
    best = window
    for i in range(k, len(numbers)):
        window += numbers[i] - numbers[i - k]   # numbers[i] comes in, numbers[i-k] goes out
        best = max(best, window)
    return best

print(max_sum([2, 1, 5, 1, 3, 2], 3))    # 9

Variable-size window

It is extended on the right and shrunk on the left when the condition breaks.

def longest_without_repeats(text):
    last = {}                  # character -> last position
    start = 0                   # left edge of the window
    best = 0
    for i, ch in enumerate(text):
        if ch in last and last[ch] >= start:
            start = last[ch] + 1          # we shrink from the left
        last[ch] = i
        best = max(best, i - start + 1)   # window [start, i]
    return best

print(longest_without_repeats("abcabcbb"))     # 3
  • Define what the window is ([start, i]) and what state you keep of it (sum, dictionary of positions, counter…).
  • Update the state when an element enters and leaves, without recomputing.
  • It works for sums, averages, substrings without repeats, at most k distinct…

You practice it in Maximum sum of k consecutive items and Longest substring without repeats.