Sliding Window

⏱ Time: O(n)💾 Space: O(1) to O(k)

Maintain a window (subarray) that slides across the array. Expand or shrink the window to find optimal subarrays that satisfy a condition. Avoids nested loops by reusing computation from the previous window position.

🎯 When to Use

  • ✓Finding max/min subarray of fixed size
  • ✓Longest/shortest substring with a condition
  • ✓Contiguous subarray problems
  • ✓Stream processing or rolling aggregates

📝 Pseudocode

Sliding Window TemplateO(n)
1function slidingWindow(arr, k):
2  windowSum = sum of first k elements
3  maxSum = windowSum
4
5  for i from k to arr.length - 1:
6    windowSum += arr[i]       // add right
7    windowSum -= arr[i - k]   // remove left
8    maxSum = max(maxSum, windowSum)
9
10  return maxSum

🏢 Real-World Use Cases

Netflix
Streaming bitrate optimization

Calculating the rolling average of network throughput over a sliding time window to adjust video quality.

Amazon
Inventory tracking

Finding the peak order period — the k-day window with the highest total orders.

💡 Practice Problems (5)

← Back to Patterns