Sliding Window
Medium
Overview (Fixed Length)
Master the fixed-size sliding window pattern: slide one element out, slide one element in.
15 min
Solve on LeetCodeWhat is a Fixed Length Window?
In a Fixed Length sliding window, the size of the window k never changes. Visualizing it is simple: imagine a rigid frame of size k sliding across your array one step at a time.
The Golden Rule:
At each step, we do exactly two things in O(1) time:
- Remove the element leaving the window (the one at
i - k). - Add the element entering the window (the one at
i).
This "Add-Remove" strategy avoids re-calculating the window content from scratch, turning an O(N*K) brute force algorithm into an O(N) linear solution.
Core Problem: Maximum Sum Subarray of Size K
The classic problem to learn this pattern:
Given an array of integers nums and an integer k, find the maximum sum of any contiguous subarray of size k.
Example:
- Input:
nums = [2, 1, 5, 1, 3, 2],k = 3 - Output:
9 - Explanation: Subarray
[5, 1, 3]has the largest sum.
Algorithm Strategy
- Initialize: Calculate the sum of the first
kelements. Set this as your initialcurrent_sumandmax_sum. - Slide: Iterate from index
kto the end of the array. - Update: For each new element at index
i:- Add
nums[i]tocurrent_sum. - Subtract
nums[i - k](the element falling out) fromcurrent_sum. - Update
max_sum = max(max_sum, current_sum).
- Add
- Return:
max_sum.
Visual Walkthrough
Step 1 / 1
Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- What is a Fixed Length Window?
- Core Problem: Maximum Sum Subarray of Size K
- Algorithm Strategy
- Visual Walkthrough
- Dry Run: [2, 1, 5, 1, 3, 2], k=3
- Edge Cases & Common Mistakes
- The Code Template
- Complexity Analysis
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.
