← Back

🪟Sliding Window Pattern

Interactive Visualization

👶Explain Like I'm 5

Imagine you're looking at houses through a car window...

You can see 3 houses at a time through your window. Instead of stopping and counting houses again and again, you just slide your window forward—remove the house that goes out of view, add the new house that comes in!

Why is this smart? Instead of counting 3 houses every time (slow! 🐌), you just subtract one and add one (fast! 🚀).

Real-world use cases:

  • Find the best N-day average stock price
  • Maximum sales in any 7-day period
  • Longest substring without repeating characters
  • Minimum window to contain all required items

Problem: Find Maximum Sum of 3 Consecutive Numbers

Array: [3,1,4,1,5,9,2,6]

3
← Left
1
4
Right →
1
5
9
2
6
Current Window
3
1
4
=
0
Current Sum
0
Max Sum
0
Window Size
3
Step
0

3

💻Code Template

Copy this pattern!
function maxSumSubarray(arr, k) {
  let maxSum = 0;
  let windowSum = 0;

  // Calculate sum of first window
  for (let i = 0; i < k; i++) {
    windowSum += arr[i];
  }
  maxSum = windowSum;

  // Slide the window
  for (let i = k; i < arr.length; i++) {
    windowSum = windowSum - arr[i - k] + arr[i];
    maxSum = Math.max(maxSum, windowSum);
  }

  return maxSum;
}

// Time: O(n) - Only go through array once!
// Space: O(1) - No extra arrays needed!

🎯When to Use Sliding Window?

Keywords in problem: “contiguous”, “subarray”, “substring”, “consecutive”
Looking for: maximum, minimum, longest, shortest within a window
Has constraint: “size K”, “at most K distinct”, “with condition X”
Naive approach: Would use nested loops (O(n²)) but sliding window makes it O(n)!