Practice: a reusable window template
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Every sliding window problem in this module is a variation of one three-step loop: expand right, shrink left when the window invariant requires it, and record the answer. Mastering how those three steps adapt across problem types lets you recognize and code any sliding window problem in minutes.
Template walk-through
Regardless of whether the window tracks a running sum, a distinct-element map, a satisfied character counter, or a monotonic ArrayDeque, the outer loop is always for (int right = 0; right < n; right++).
- Identify whether the problem asks for a fixed length k, longest valid, shortest valid, or subarray count.
- Choose the window state (long sum, int[128] freq, HashMap, or ArrayDeque) that updates in O(1) on add/remove.
- Place the answer update inside the while loop (for shortest valid) or after the while loop (for longest valid and atMost counting).
Example 1 · Side-by-side comparison: Longest vs. Shortest vs. Count on the same array
public class UnifiedWindowTemplateDemo { public static int longestSumAtMost(int[] nums, int k) { int left = 0, sum = 0, best = 0; for (int right = 0; right < nums.length; right++) { sum += nums[right]; while (sum > k) sum -= nums[left++]; best = Math.max(best, right - left + 1); } return best; }
public static int shortestSumAtLeast(int[] nums, int k) { int left = 0, sum = 0, best = Integer.MAX_VALUE; for (int right = 0; right < nums.length; right++) { sum += nums[right]; while (sum >= k) { best = Math.min(best, right - left + 1); sum -= nums[left++]; } } return best == Integer.MAX_VALUE ? 0 : best; }
public static int countSumAtMost(int[] nums, int k) { int left = 0, sum = 0, count = 0; for (int right = 0; right < nums.length; right++) { sum += nums[right]; while (sum > k) sum -= nums[left++]; count += right - left + 1; } return count; }
public static void main(String[] args) { int[] nums = {2, 1, 3, 2, 4, 1}; System.out.println("Longest sum <= 6: " + longestSumAtMost(nums, 6)); System.out.println("Shortest sum >= 6: " + shortestSumAtLeast(nums, 6)); System.out.println("Count sum <= 6: " + countSumAtMost(nums, 6)); }}Longest sum <= 6: 3 Shortest sum >= 6: 2 Count sum <= 6: 13
What this code does
- Notice that longestSumAtMost and countSumAtMost have the exact same loop body except for the last line (Math.max vs count +=).
- shortestSumAtLeast flips the while condition to >= k and moves the answer update inside the while loop.
Only the inner shrink condition and the placement of the answer update change across the four variations:
- Fixed-size window (k): Shrink once when
right >= k(left = right - k), and record the answer whenright >= k - 1. - Longest valid window: Shrink
while (window is invalid), and recordmaxLen = Math.max(maxLen, right - left + 1)after thewhileloop. - Shortest valid window: Shrink
while (window is valid), and recordminLen = Math.min(minLen, right - left + 1)inside thewhileloop before removingleft. - Count valid subarrays (
atMost(k)): Shrinkwhile (metric > k), and addright - left + 1after thewhileloop. Forexactly(k), returnatMost(k) - atMost(k - 1).
Mixed window problems
In interviews, sliding window problems are often disguised as other operations.
Example 2 · Sorting + Sliding Window: Frequency of the Most Frequent Element
import java.util.Arrays;
public class MaxFrequencyAfterIncrementsDemo { public static int maxFrequency(int[] nums, int k) { Arrays.sort(nums); int left = 0; long windowSum = 0; int maxFreq = 0;
for (int right = 0; right < nums.length; right++) { windowSum += nums[right]; while ((long) (right - left + 1) * nums[right] - windowSum > k) { windowSum -= nums[left]; left++; } maxFreq = Math.max(maxFreq, right - left + 1); } return maxFreq; }
public static void main(String[] args) { int[] nums = {1, 4, 8, 13}; System.out.println("Max frequency (k=5): " + maxFrequency(nums, 5)); int[] nums2 = {1, 2, 4}; System.out.println("Max frequency (k=5): " + maxFrequency(nums2, 5)); }}Max frequency (k=5): 2 Max frequency (k=5): 3
What this code does
- After sorting, the cheapest elements to increment up to nums[right] are the ones immediately to its left in [left .. right].
- The cost to raise all elements in [left .. right] to nums[right] is (right - left + 1L) * nums[right] - windowSum.
Example 3 · Grumpy Bookstore Owner: baseline sum + fixed-window gain
public class GrumpyBookstoreDemo { public static int maxSatisfied(int[] customers, int[] grumpy, int minutes) { int baseSatisfied = 0; int windowGain = 0; int maxGain = 0;
for (int right = 0; right < customers.length; right++) { if (grumpy[right] == 0) { baseSatisfied += customers[right]; } else { windowGain += customers[right]; } if (right >= minutes && grumpy[right - minutes] == 1) { windowGain -= customers[right - minutes]; } if (right >= minutes - 1) { maxGain = Math.max(maxGain, windowGain); } } return baseSatisfied + maxGain; }
public static void main(String[] args) { int[] customers = {1, 0, 1, 2, 1, 1, 7, 5}; int[] grumpy = {0, 1, 0, 1, 0, 1, 0, 1}; System.out.println("Max satisfied customers: " + maxSatisfied(customers, grumpy, 3)); }}Max satisfied customers: 16
What this code does
- Customers arriving when grumpy[i] == 0 are always satisfied (baseSatisfied = 1 + 1 + 1 + 7 = 10).
- A fixed window of length minutes=3 finds the maximum extra customers saved during grumpy minutes (maxGain = 1 + 5 = 6 in the last 3 minutes), giving 10 + 6 = 16.
- End removals (Maximum Points from Cards, Minimum Operations to Reduce X to Zero): Removing elements from the two ends of an array of length n leaves a contiguous middle window of length n - k (fixed) or sum total - x (variable).
- Sorting + Sliding Window (Frequency of the Most Frequent Element): When element order does not matter and you want to increment elements by at most k total operations so they all equal the largest element in a group, sort the array first! Then any group of equalized elements is a contiguous window
[left .. right]whose cost to raise everything tonums[right]is(long) (right - left + 1) * nums[right] - windowSum. - Ask: 'If I fix the right endpoint, does the optimal left endpoint move monotonically to the right?' If yes, use a sliding window.
- When order does not matter and you want elements close in value, sort first and run a sliding window on the sorted array.
Complexity of window solutions
Why is every sliding window in this module O(n) time (or O(n log n) if sorting precedes it)? Because of amortized two-pointer analysis:
rightstarts at0and increments once per outer iteration (n times).leftstarts at0, only increments (left++), and never exceeds n (at most n times).- Each
add(right)andremove(left)performs O(1) work on a primitive sum, fixed array,HashMap, or monotonicArrayDeque.
Therefore, the body of the inner while loop executes at most n times across the entire algorithm, not n times per outer iteration! Total work is bounded by 2n constant-time operations: O(n) time.
Finish up
Mark complete & continue
Next: Prefix sum arrays