What is the Sliding Window Pattern?
Sliding Window is a technique for finding a subarray or substring that optimizes a certain condition. Instead of checking every possible subarray (O(n²) or O(n³)), the window "slides" through the array in O(n) time.
Fixed-Size vs Dynamic-Size Windows
| Type | Window Size | When to Use | Example |
|---|---|---|---|
| Fixed | Constant k | "Find max sum of k consecutive elements" | Max Average Subarray I |
| Dynamic | Variable | "Find longest substring with condition" | Longest Substring Without Repeating Characters |
Fixed-Size Sliding Window Template
function fixedWindow(nums, k) {
let windowSum = 0, maxSum = 0;
// Build initial window
for (let i = 0; i < k; i++) {
windowSum += nums[i];
}
maxSum = windowSum;
// Slide the window
for (let i = k; i < nums.length; i++) {
windowSum += nums[i] - nums[i - k]; // add new, remove old
maxSum = Math.max(maxSum, windowSum);
}
return maxSum;
}
Dynamic-Size Sliding Window Template
function dynamicWindow(s) {
let left = 0, maxLen = 0;
const seen = new Set();
for (let right = 0; right < s.length; right++) {
// Expand window by adding s[right]
while (seen.has(s[right])) {
// Contract window from left until valid
seen.delete(s[left]);
left++;
}
seen.add(s[right]);
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
Top Sliding Window LeetCode Problems
| Problem | Difficulty | Window Type |
|---|---|---|
| 3. Longest Substring Without Repeating Characters | Medium | Dynamic |
| 76. Minimum Window Substring | Hard | Dynamic |
| 209. Minimum Size Subarray Sum | Medium | Dynamic |
| 239. Sliding Window Maximum | Hard | Fixed |
| 643. Maximum Average Subarray I | Easy | Fixed |
| 424. Longest Repeating Character Replacement | Medium | Dynamic |
| 438. Find All Anagrams in a String | Medium | Fixed |
| 567. Permutation in String | Medium | Fixed |
How to Recognize Sliding Window Problems
Look for these keywords in the problem statement:
- "Longest/shortest substring or subarray"
- "Consecutive elements"
- "Window of size k"
- "Contains all characters"
- "Maximum sum of k elements"
- "At most K distinct characters"
How GhOst Helps with Sliding Window Problems
- Instant pattern recognition: Identifies Sliding Window from keywords in the problem
- Template selection: Chooses fixed vs dynamic based on the question
- Edge cases: Empty string, all same characters, no valid window
- Optimization hints: Suggests Hash Map vs Set vs Deque for the window
Frequently Asked Questions
O(n) in most cases. Each element is added and removed from the window at most once. Space is O(k) or O(min(m, n)) depending on the data structure used.
Use a monotonic Deque for "maximum in sliding window" problems where you need to find the max of each window in O(n) time.
Sliding Window maintains a contiguous subarray/substring and typically moves both pointers in the same direction. Two Pointers often starts from opposite ends or moves independently.