VISHAL CHERUPALLYVC
← Python Coding

Mastering
Sliding Window
in Python

A powerful pattern to optimise problems involving subarrays and substrings — without nested loops.

Sliding window is a technique where we maintain a window (a contiguous subarray) and move it step-by-step instead of recomputing values from scratch on every iteration. The key observation: when you slide the window one position, you only need to account for one element entering and one leaving.

The window size stays constant. Compute the first window sum, then slide by adding the incoming element and subtracting the outgoing one.

def max_sum_subarray(arr, k):
    window_sum = sum(arr[:k])   # first window
    max_sum = window_sum

    for i in range(k, len(arr)):
        window_sum += arr[i]        # add incoming
        window_sum -= arr[i - k]    # remove outgoing
        max_sum = max(max_sum, window_sum)

    return max_sum

Complexity: O(n) time, O(1) space. The naive approach (recompute each window from scratch) is O(n·k).

Here the window expands with the right pointer, and contracts from the left when a constraint is violated.

def longest_substring(s):
    seen  = set()
    left  = 0
    max_len = 0

    for right in range(len(s)):
        while s[right] in seen:   # constraint violated
            seen.remove(s[left])
            left += 1             # shrink from left

        seen.add(s[right])
        max_len = max(max_len, right - left + 1)

    return max_len

Fixed window (k)

Window size is constant. Typical in max/min sum of k elements.

Variable window

Window expands until a constraint breaks, then contracts.

Substring problems

Use a frequency map inside the window to track character counts.

Min / max window

Deque-based windows give O(n) for maximum-in-sliding-window.

  • Data is a contiguous subarray or substring
  • You need to optimise a nested loop over adjacent elements
  • The problem mentions 'maximum / minimum of exactly k elements'
  • Constraints on a subarray can be maintained incrementally