Data Structures20 min read

Sliding Window

Learn the sliding window technique to process subarrays efficiently, like max sum of k items, longest substring problems, and stream-like processing.

David Miller
October 25, 2025
5.0k111

Sliding window is used when you need continuous chunks of data.

Example:

  • max sum of 3 consecutive days
  • longest substring without repeating
  • windowed averages

Example: max sum of k consecutive items

def max_sum_k(nums, k):
    window_sum = sum(nums[:k])
    best = window_sum

    for i in range(k, len(nums)):
        window_sum += nums[i] - nums[i-k]
        best = max(best, window_sum)

    return best

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

Why this is efficient

Instead of summing each window from scratch,
you update by removing left item and adding right item.

Graph: window movement

flowchart LR
  A[Window start] --> B[Shift right]
  B --> C[Drop left]
  C --> D[Add new right]

Remember

  • Great for consecutive subarray/substrings
  • Converts repeated work into one-pass logic
  • Often changes O(n*k) into O(n)
#Python#Intermediate#Techniques