When solving problems with arrays or strings, sometimes recalculating everything from scratch is wasteful. That's where the Sliding Window pattern comes in.
It's a smart way to keep track of a "window" (a subset of data) as you move through a collection without redoing all the work.
This technique pops up a lot in coding interviews, optimization problems, and real-world performance issues.
What is the Sliding Window Pattern?
The idea is simple:
👉 Imagine a "window" that slides across your array or string.
👉 At each step, you only update the new part of the window instead of recalculating everything.
This reduces unnecessary computations and makes your solution much faster.
Think of it like looking at the scenery through a moving train window you don't re-see the whole country, just the new part as the train moves forward.
Example Problem: Find the Maximum Sum of a Subarray of Length n
We'll write a function called maxSubarraySum that finds the largest sum of n consecutive numbers in an array.
Example:
javascriptmaxSubarraySum([2, 6, 9, 2, 1, 8, 5, 6, 3], 3); // Output: 19 (because 8 + 5 + 6 = 19)
The Naive Solution
The most basic way is to use two loops:
javascriptfunction maxSubarraySum(arr, num) { if (num > arr.length) return null; let max = -Infinity; for (let i = 0; i < arr.length - num + 1; i++) { let temp = 0; for (let j = 0; j < num; j++) { temp += arr[i + j]; } if (temp > max) { max = temp; } } return max; }
This works, but the time complexity is O(n²). For large arrays, that's way too slow.
The Refactored Solution (Using Sliding Window)
Here's where the pattern shines:
- Calculate the sum of the first n numbers.
- Store it as the current maximum.
- Slide the window forward: subtract the number that's leaving, add the new number that's entering.
- Update the maximum as you go.
javascriptfunction maxSubarraySum(arr, num) { if (num > arr.length) return null; let maxSum = 0; let tempSum = 0; // Step 1: sum first window for (let i = 0; i < num; i++) { maxSum += arr[i]; } tempSum = maxSum; // Step 2: slide the window for (let i = num; i < arr.length; i++) { tempSum = tempSum - arr[i - num] + arr[i]; maxSum = Math.max(maxSum, tempSum); } return maxSum; }
This solution runs in O(n) time, a massive improvement.
Why This Works
The key insight is: 👉 Instead of recalculating the whole sum each time, just adjust it by removing the old value and adding the new one.
It's like keeping a running balance in your wallet instead of recounting all your money every time you buy something.
Takeaway
The Sliding Window pattern is your go-to tool when:
- You need to check subarrays or substrings.
- You're working with consecutive sequences.
- Performance matters.
