Sliding WindowSliding Window

Sliding Window (Variable Size)

Grow a window from the right while a condition holds and shrink it from the left when it breaks, finding the longest or shortest valid contiguous subarray in O(n).

Learn Sliding Window (Variable Size) →
2
0
3
1
1
2
2
3
4
4
3
5
1
6
5
7
2
8
1/27Find the shortest subarray with sum ≥ 7. Because all values are positive, growing the window only increases the sum and shrinking only decreases it — that monotonicity makes two pointers valid.
Current windowEntering (r)Shrunk awayBest window
1l = 0, sum = 0, best = ∞
2for r in 0 .. n-1:
3 sum += a[r]
4 while sum >= target:
5 best = min(best, r - l + 1)
6 sum -= a[l]; l += 1
7return best (or 0 if never reached)
Variables
l0
sum0
best
target7
Complexity
best O(n)
avg O(n)
worst O(n)
space O(1)
Speed