arr=[2,1,5,1,3,2,1,4] · k=3 · max sum subarray of size k
2
0
1
1
5
2
1
3
3
4
2
5
1
6
4
7
window [0..2]
8
best [0..2]
8
Initial window [0..2] sum = 8.
Start with first k=3 elements as initial window.
start
1 / 13
SPD0.5×
click to pause · hover for controls · fullscreen for more

Sliding Window

Turn O(n²) subarray problems into O(n) with a moving window

Visual by thisgirltech

IntermediateConcept

The sliding window pattern converts O(n²) subarray problems into O(n). Instead of re-scanning from scratch every time, you maintain a window of elements and update it incrementally — adding one element to the right, removing one from the left.

There are two variants: fixed-size (slide a window of constant width k across the array) and variable-size (expand right until a condition is met, then shrink from the left to optimise).

Window as a view

The window is just two pointers — left and right — defining which elements are currently 'in scope'. You don't store the elements separately, you just track the boundaries.

Incremental updates

Instead of recomputing the sum of k elements every step (O(k)), sliding window does: sum = sum - arr[left] + arr[right+1]. One operation per slide — O(1).

Pointers only move right

Both left and right pointers only ever move rightward. Each element is added once and removed at most once. Total operations: 2n. That's O(n) regardless of window size.

Fixed vs variable

Fixed: window size k is given, slide one step at a time. Variable: no fixed size — expand right to satisfy a condition, shrink left to optimise, track the best window seen.

TIP

The key insight for variable window: right only moves forward, left only moves forward. Each element enters the window once and leaves at most once. That's why it's O(n) even with the while loop inside the for loop.

COLOUR LEGEND

Window expanding (right moves)
Window shrinking (left moves)
New best found