Skip to lesson

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++).

  1. Identify whether the problem asks for a fixed length k, longest valid, shortest valid, or subarray count.
  2. Choose the window state (long sum, int[128] freq, HashMap, or ArrayDeque) that updates in O(1) on add/remove.
  3. 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

UnifiedWindowTemplateDemo.javaJava
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));    }}
Output
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:

  1. Fixed-size window (k): Shrink once when right >= k (left = right - k), and record the answer when right >= k - 1.
  2. Longest valid window: Shrink while (window is invalid), and record maxLen = Math.max(maxLen, right - left + 1) after the while loop.
  3. Shortest valid window: Shrink while (window is valid), and record minLen = Math.min(minLen, right - left + 1) inside the while loop before removing left.
  4. Count valid subarrays (atMost(k)): Shrink while (metric > k), and add right - left + 1 after the while loop. For exactly(k), return atMost(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

MaxFrequencyAfterIncrementsDemo.javaJava
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));    }}
Output
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

GrumpyBookstoreDemo.javaJava
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));    }}
Output
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 to nums[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:

  • right starts at 0 and increments once per outer iteration (n times).
  • left starts at 0, only increments (left++), and never exceeds n (at most n times).
  • Each add(right) and remove(left) performs O(1) work on a primitive sum, fixed array, HashMap, or monotonic ArrayDeque.

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.

To preserve O(n) time, never scan the entire window or call s.substring(left, right + 1) inside the loop; maintain incremental state and slice substrings only once at the end.

Finish up

Mark complete & continue

Next: Prefix sum arrays