πͺ Sliding Window
One-line summary: Move a window over the input to solve subarray/substring problems in O(n) instead of O(nΒ²).
π‘ Core Conceptsβ
What is Sliding Window?β
Sliding Window is an optimization technique that transforms nested loops into a single loop by maintaining a window (subarray/substring) that slides across the input data.
Types of Sliding Windowβ
1οΈβ£ Fixed-Size Windowβ
- Window size remains constant (exactly K elements)
- Move window one position at a time
- Perfect for: "Find max sum of K consecutive elements"
2οΈβ£ Dynamic/Variable Windowβ
- Window size changes based on conditions
- Expand right pointer to include new elements
- Shrink left pointer when constraint is violated
- Perfect for: "Find smallest subarray with sum β₯ target"
Key Sliding Window Propertiesβ
- Linear Time: Reduces O(nΒ²) brute force to O(n)
- Two Pointers: Uses left and right pointers to define window boundaries
- State Tracking: Maintains window state (sum, count, frequency, etc.)
- Constraint-Based: Window adjusts based on problem constraints
When to Use Sliding Window?β
β Perfect for:
- Subarray/substring problems with contiguous elements
- "Find maximum/minimum in window" problems
- "Count subarrays with property X" problems
- String pattern matching and anagram problems
- "Longest/shortest subarray with condition" problems
β Not suitable for:
- Non-contiguous subsequence problems
- Problems requiring global optimization (use DP)
- Tree/graph traversal problems
Related Patternsβ
- Overlapping Intervals: Sort by start time, merge when
intervals[i].start <= lastEnd - Two Pointers: Similar concept but for different problem types
- Prefix Sum: Can be combined with sliding window for range queries
π Visual Learningβ
Sliding Window Technique Over
β
Enhanced Visualization Featuresβ
The enhanced animation demonstrates:
- Dynamic window expansion and contraction with smooth visual transitions
- Real-time sum calculation showing constraint validation
- Color-coded status indicators (valid/invalid states)
- Step-by-step algorithm phases with detailed explanations
- Interactive pointer movements showing left and right boundary adjustments
- Visual constraint checking highlighting when sum exceeds target
.svg)
Step-by-step visualization of how the sliding window moves across arrays to solve subarray problems
Dynamic Window Expansionβ
Interactive demonstration of window expansion and contraction based on problem constraints
Window Size Comparisonβ
Visual comparison between fixed-size and variable-size sliding window approaches
Memory Usage Optimizationβ
Understanding space complexity and memory patterns in sliding window algorithms
Time & Space Complexityβ
| Variant | Time | Space |
|---|---|---|
| Fixed window | O(n) | O(1) or O(k) |
| Dynamic window | O(n) | O(k) |
| Merge intervals | O(n log n) | O(n) |
Common Patternsβ
Fixed Window β Max Sum of K Elementsβ
function maxSumK(arr, k) {
let windowSum = arr.slice(0, k).reduce((s, x) => s + x, 0);
let maxSum = windowSum;
for (let i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k];
maxSum = Math.max(maxSum, windowSum);
}
return maxSum;
}
Dynamic Window β Longest Substring Without Repeatβ
function lengthOfLongestSubstring(s) {
const seen = new Map();
let left = 0, maxLen = 0;
for (let right = 0; right < s.length; right++) {
if (seen.has(s[right])) left = Math.max(left, seen.get(s[right]) + 1);
seen.set(s[right], right);
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
Merge Intervalsβ
function merge(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const result = [intervals[0]];
for (const [s, e] of intervals.slice(1)) {
if (s <= result[result.length - 1][1]) result[result.length - 1][1] = Math.max(result[result.length - 1][1], e);
else result.push([s, e]);
}
return result;
}
Pitfallsβ
- Dynamic window: shrink from left until constraint is satisfied again β don't reset the window
- Fixed window: slide by adding right element and subtracting element that just left
Practice Problemsβ
| LC 904 β Fruit Into Baskets | Medium | | | LC 159 β Longest Substring with At Most Two Distinct Characters | Medium | | | LC 209 β Minimum Size Subarray Sum | Medium | | | LC 340 β Longest Substring with At Most K Distinct Characters | Medium | | | LC 395 β Longest Substring with At Least K Repeating Characters | Medium | | | LC 435 β Non-overlapping Intervals | Medium | | | LC 452 β Minimum Number of Arrows to Burst Balloons | Medium | | | LC 713 β Subarray Product Less Than K | Medium | | | LC 930 β Binary Subarrays With Sum | Medium | | | LC 986 β Interval List Intersections | Medium | | | LC 992 β Subarrays with K Different Integers | Medium | | | LC 1208 β Get Equal Substrings Within Budget | Medium | | | LC 1248 β Count Number of Nice Subarrays | Medium | | | LC 1438 β Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit | Medium | | | LC 1493 β Longest Subarray of 1's After Deleting One Element | Medium | | | LC 1658 β Minimum Operations to Reduce X to Zero | Medium | | | LC 1695 β Maximum Erasure Value | Medium | | | LC 1838 β Frequency of the Most Frequent Element | Medium | | | LC 2024 β Maximize the Confusion of an Exam | Medium | | | CC β Maximum Unique Subarray Window (UNQEQ) | Medium | | | CC β Dynamic Window (DYNWIN) | Medium | | | CC β Interval Merging (INTMERGE) | Medium | | | CC β Substring Matching (SUBMATCH) | Medium | | | LC 76 β Minimum Window Substring | Hard | | | LC 239 β Sliding Window Maximum | Hard | | | LC 30 β Substring with Concatenation of All Words | Hard | | | LC 84 β Largest Rectangle in Histogram | Hard | | | LC 85 β Maximal Rectangle | Hard | | | LC 632 β Smallest Range Covering Elements from K Lists | Hard | | | LC 727 β Minimum Window Subsequence | Hard | | | LC 862 β Shortest Subarray with Sum at Least K | Hard | | | LC 1425 β Constrained Subsequence Sum | Hard | | | LC 1499 β Max Value of Equation | Hard | | | LC 1687 β Delivering Boxes from Storage to Ports | Hard | | | LC 1793 β Maximum Score of a Good Subarray | Hard | | | LC 2009 β Minimum Number of Operations to Make Array Continuous | Hard | | | LC 2444 β Count Subarrays With Fixed Bounds | Hard | | | CC β Advanced Sliding Window (ADVSLIDE) | Hard | | | CC β Complex Window Operations (COMPLEXWIN) | Hard | | | CC β Sliding Window Maximum (SLIDEMAX) | Hard | |
Related Topicsβ
- Two Pointers β sliding window is two pointers with a constraint
- Hashing β frequency maps used inside windows
- Prefix Sum
β Back to Home Β· Β© sparshjaswal