Home
DSA Course
Arrays
Sliding Window
Sliding Window
Visualize the Sliding Window technique to efficiently process subarrays.
Current Sum
0
Max Sum
-
Ready to find max sum.
2
01
15
21
33
42
59
67
7See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.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".
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
