Home
DSA Visualizer
Arrays
Sliding Window
Sliding Window
The sliding window technique processes subarrays efficiently by moving a window across the array instead of recomputing each subarray from scratch.
WINDOW 3
FIRST WINDOW
0
1
2
3
4
5
6
7
Window sum
8
Best so far
8
Sum the first 3 elements: 2 + 1 + 5 = 8. That is the only full sum this algorithm ever computes.
Next
Slide right: add 1, drop 2 → 7. Two operations, not 3. Best stays 8.
Array
Window
Intuition
Instead of re-calculating the sum of every subarray from scratch (O(n*k)), we can "slide" the window by one position: add the new element entering the window and subtract the element leaving it. This reduces the complexity to O(n).
Concept
- Window: A range of elements [start, end].
- Slide: Move start and end by 1.
- Optimization: Reuse the result of the previous window.
How it Works
Algorithm:
- Calculate sum of first
kelements. - Set
maxSum = currentSum. - Loop from
i = kton-1: currentSum += arr[i](Add new)currentSum -= arr[i-k](Remove old)- Update
maxSumif needed.
Step-by-Step Breakdown
Watch the visualization:
- Observe the window moving one step at a time.
- See how the sum updates instantly by just +1 and -1 operation.
When to Use
- Finding subarrays of fixed size K with specific properties (max sum, min avg).
- Finding longest/shortest subarray with specific properties (dynamic window).
- String problems (longest substring without repeating characters).
When NOT to Use
- When the problem requires non-contiguous elements (subsequences).
How to Identify
"Subarray of size K", "Longest substring", "Consecutive elements".
Preparing for interviews? This topic is also taught as a pattern:
Introduction to Sliding Window
Applying for software engineering roles? Free, no sign-up:
