Day 73:
The Sliding Window Technique — Why It’s a Must-Know for Every LeetCoder
Let’s say you’re given this simple problem:
“Find the maximum sum of any 3 consecutive numbers in an array.”
You have this array:
js
nums = [1, 2, 3, 4, 5, 6]
The brute-force way?
Check all groups of 3:
1+2+3 = 6
2+3+4 = 9
3+4+5 = 12
4+5+6 = 15
Answer: 15
But time complexity = O(n * k) if k is the window size.
Now imagine your array has 1 million numbers and you need the sum of every 1000 consecutive numbers — suddenly, brute force isn’t so cute.
Enter the Sliding Window Technique.
How It Works
You build a “window” of size k (in this case, 3), calculate the sum once, and then just “slide” the window one step at a time:
Initial sum: 1 + 2 + 3 = 6
Slide window right:
Remove 1 (leftmost)
Add 4 (next in array)
→ New sum: 6 - 1 + 4 = 9
Repeat:
Remove 2, add 5 → 9 - 2 + 5 = 12
Remove 3, add 6 → 12 - 3 + 6 = 15
Same result, but in O(n) time.
This is what Sliding Window does:
It avoids repetition by reusing previous calculations and only adjusting what changed — making it a go-to for efficient algorithms.
Where You’ll Use It on LeetCode
The Sliding Window technique shines in problems involving:
Subarrays or substrings
Consecutive or fixed-size elements
Dynamic tracking (length, sum, uniqueness)
Examples:
Longest Substring Without Repeating Characters
Maximum Sum Subarray of Size K
Minimum Size Subarray Sum
Permutation in String
Contains Duplicate II
Visualize It Like This:
Imagine dragging a box across your array or string.
At every move, you only care about the element that enters and the one that exits.
The rest of the window stays intact — so your calculations are fast, clean, and focused.
When to Reach for Sliding Window:
The question mentions “subarray” or “substring”
You’re given a length or range constraint
You need to find “maximum/minimum/longest/shortest” something
Brute force is too slow, and you want to cut it to O(n)
From Two Pointers to Sliding Window
If you’ve mastered the Two Pointer approach, Sliding Window is your next step.
They’re cousins — both involve scanning with two markers — but Sliding Window is like a smarter version that carries memory with it.
You don’t restart; you slide.