- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- The Sliding Window Technique
Two Pointers and Sliding Window
The Sliding Window Technique
If a problem asks for the longest or shortest contiguous run that satisfies something, it is a sliding window. That single recognition saves more time than any other pattern here.
The idea
Keep a start and an end index. Extend the end to grow the window. When the window breaks the rule, move the start until it is valid again. Each index moves forward at most once, so the whole scan is O(n) even though it looks like a nested loop.
Fixed window
When the size is given, slide it and adjust by one at each step.
Best average of k consecutive
javascript
function maxSumOfK(nums, k) {
let sum = 0
for (let i = 0; i < k; i++) sum += nums[i]
let best = sum
for (let i = k; i < nums.length; i++) {
// Add the new element, drop the one that left.
sum += nums[i] - nums[i - k]
best = Math.max(best, sum)
}
return best
}
console.log(maxSumOfK([2, 1, 5, 1, 3, 2], 3)) // 9