Skip to lesson

Variable-size windows

When a problem does not fix the window length k, and instead asks for the longest subarray with sum at most S or the shortest subarray with sum at least target, the window must breathe: growing on the right and shrinking from the left.

Grow on the right, shrink on the left

A variable-size window grows on the right and shrinks on the left to keep a condition true, such as a sum not above a limit.

A variable-size sliding window uses two pointers, left = 0 and right = 0, where the outer for loop advances right one step at a time and an inner while loop advances left whenever needed.

Example 1 · Longest subarray with sum at most S and at most k zeroes

LongestValidWindowDemo.javaJava
public class LongestValidWindowDemo {    public static int longestSubarraySumAtMost(int[] nums, int maxSum) {        int left = 0;        long sum = 0;        int best = 0;        for (int right = 0; right < nums.length; right++) {            sum += nums[right];            while (sum > maxSum) {                sum -= nums[left];                left++;            }            best = Math.max(best, right - left + 1);        }        return best;    }
    public static int longestOnesWithKFlips(int[] bits, int k) {        int left = 0;        int zeroes = 0;        int best = 0;        for (int right = 0; right < bits.length; right++) {            if (bits[right] == 0) {                zeroes++;            }            while (zeroes > k) {                if (bits[left] == 0) {                    zeroes--;                }                left++;            }            best = Math.max(best, right - left + 1);        }        return best;    }
    public static void main(String[] args) {        int[] tasks = {3, 1, 2, 7, 4, 2, 1, 1, 5};        System.out.println("Longest sum <= 8: " + longestSubarraySumAtMost(tasks, 8));
        int[] bits = {1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0};        System.out.println("Longest 1s with k=2 flips: " + longestOnesWithKFlips(bits, 2));    }}
Output
Longest sum <= 8: 4
Longest 1s with k=2 flips: 6

What this code does

  • For longest valid window problems, the while loop repairs an invalid window (sum > maxSum or zeroes > k), and best is updated after the while loop.
  • In tasks, [4, 2, 1, 1] has sum 8 and length 4. In bits, indices 5..10 ([0, 1, 1, 1, 1, 0]) has two zeroes and length 6.

Even though there is a while loop inside a for loop, left only moves forward from 0 to n across the entire execution, so the total work is still O(n).

Variable-size windows fall into two symmetric templates depending on whether you want the longest valid window or the shortest valid window:

  • Longest valid window (e.g., sum ≤ S, or at most k zeroes): expand right, then while (window is invalid) shrink left++, and finally record maxLen = Math.max(maxLen, right - left + 1) once the window is valid.
  • Shortest valid window (e.g., sum ≥ target): expand right, then while (window is valid) record minLen = Math.min(minLen, right - left + 1) inside the while loop and shrink left++ to see if an even shorter window ending at right is also valid.
  • Longest valid window: shrink while INVALID, update answer AFTER the while loop.
  • Shortest valid window: update answer and shrink while VALID (INSIDE the while loop).
  • Amortized complexity: right increments n times, left increments at most n times -> at most 2n pointer moves -> O(n) time.

Smallest subarray with sum at least a target

Given an array of positive integers nums and a positive integer target, find the minimal length of a contiguous subarray [left .. right] whose sum is at least target, or return 0 if none exists.

  1. Initialize left = 0, windowSum = 0, and minLen = Integer.MAX_VALUE.
  2. For each right from 0 to nums.length - 1, add nums[right] to windowSum.
  3. While windowSum >= target: update minLen = Math.min(minLen, right - left + 1), subtract nums[left] from windowSum, and increment left.
  4. Return minLen == Integer.MAX_VALUE ? 0 : minLen.

Shortest Subarray With Sum ≥ 7 on nums = [2, 3, 1, 2, 4, 3]

Step 1 of 6

Array: 2, 3, 1, 2, 4, 3. left at index 0. right at index 2.
sum
6
target
7
minLen
INF
Expand right through 0..2: window [2, 3, 1] has sum = 6 < 7, so keep expanding right.

Example 2 · Brute force: try every start and end (O(n²) time, O(1) space)

MinSubArrayLenBrute.javaJava
public class MinSubArrayLenBrute {    public static int minSubArrayLen(int target, int[] nums) {        int minLen = Integer.MAX_VALUE;        for (int start = 0; start < nums.length; start++) {            long sum = 0;            for (int end = start; end < nums.length; end++) {                sum += nums[end];                if (sum >= target) {                    minLen = Math.min(minLen, end - start + 1);                    break;                }            }        }        return minLen == Integer.MAX_VALUE ? 0 : minLen;    }
    public static void main(String[] args) {        int[] nums = {2, 3, 1, 2, 4, 3};        System.out.println("Min len for target 7: " + minSubArrayLen(7, nums));        System.out.println("Min len for target 100: " + minSubArrayLen(100, nums));    }}
Output
Min len for target 7: 2
Min len for target 100: 0

What this code does

  • Every start index grows to the right until the sum reaches the target. The running sum avoids a third loop, but each start still rescans many numbers.
  • All numbers are positive, so a window that already reaches the target only gets longer when it grows. That lets left move forward without ever going back.

Example 3 · Optimal: grow on the right, shrink on the left (O(n) time, O(1) space)

MinSubArrayLenDemo.javaJava
public class MinSubArrayLenDemo {    public static int minSubArrayLen(int target, int[] nums) {        int left = 0;        long windowSum = 0;        int minLen = Integer.MAX_VALUE;
        for (int right = 0; right < nums.length; right++) {            windowSum += nums[right];            while (windowSum >= target) {                minLen = Math.min(minLen, right - left + 1);                windowSum -= nums[left];                left++;            }        }        return minLen == Integer.MAX_VALUE ? 0 : minLen;    }
    public static void main(String[] args) {        int[] nums = {2, 3, 1, 2, 4, 3};        System.out.println("Min len for target 7: " + minSubArrayLen(7, nums));        System.out.println("Min len for target 100: " + minSubArrayLen(100, nums));    }}
Output
Min len for target 7: 2
Min len for target 100: 0

What this code does

  • The window [4, 3] at indices 4..5 has sum 7 >= 7 and length 2.
  • When no subarray reaches target 100, minLen stays Integer.MAX_VALUE and the method returns 0.
  • Why it is faster: left and right only move forward, so each number is added once and subtracted at most once: about 2n steps instead of n² / 2.

Let us hand-trace nums = [2, 3, 1, 2, 4, 3] with target = 7:

  • right = 0..3: window [2, 3, 1, 2] reaches sum = 8 >= 7. Inside the while (sum >= 7) loop, we record length 4, subtract nums[0] = 2 (left = 1, sum = 6 < 7).
  • right = 4: add 4 (sum = 10 >= 7). Record length 4 ([3, 1, 2, 4]), subtract 3 (left = 2, sum = 7 >= 7). Still valid! Record length 3 ([1, 2, 4]), subtract 1 (left = 3, sum = 6 < 7).
  • right = 5: add 3 (sum = 9 >= 7). Record length 3 ([2, 4, 3]), subtract 2 (left = 4, sum = 7 >= 7). Still valid! Record length 2 ([4, 3]), subtract 4 (left = 5, sum = 3 < 7).

The minimum length found is 2.

Order of execution

Order one step of the window loop

Tap the steps in the order one pass of the for loop runs them.

Why negative numbers break this window

Why did the problem statement require positive integers? Because shrinking left++ assumes monotonicity: removing nums[left] is guaranteed to decrease windowSum, and advancing right++ is guaranteed to increase windowSum.

Example 4 · Counterexample showing why negative numbers break the naive sum window

NegativeCounterexampleDemo.javaJava
public class NegativeCounterexampleDemo {    public static int naiveWindowShortestAtLeast(int[] nums, int target) {        int left = 0, sum = 0, minLen = Integer.MAX_VALUE;        for (int right = 0; right < nums.length; right++) {            sum += nums[right];            while (left <= right && sum >= target) {                minLen = Math.min(minLen, right - left + 1);                sum -= nums[left++];            }        }        return minLen == Integer.MAX_VALUE ? 0 : minLen;    }
    public static int bruteForceShortestAtLeast(int[] nums, int target) {        int minLen = Integer.MAX_VALUE;        for (int i = 0; i < nums.length; i++) {            int sum = 0;            for (int j = i; j < nums.length; j++) {                sum += nums[j];                if (sum >= target) {                    minLen = Math.min(minLen, j - i + 1);                }            }        }        return minLen == Integer.MAX_VALUE ? 0 : minLen;    }
    public static void main(String[] args) {        int[] nums = {1, -3, 5};        int target = 4;        System.out.println("Naive window result: " + naiveWindowShortestAtLeast(nums, target));        System.out.println("True shortest length: " + bruteForceShortestAtLeast(nums, target));    }}
Output
Naive window result: 0
True shortest length: 1

What this code does

  • In nums = [1, -3, 5] with target = 4, as right reaches index 2, the full sum is 1 + (-3) + 5 = 3 < 4.
  • Because 3 < 4, the naive while (sum >= target) never runs and never removes 1 and -3 to uncover the single element [5] >= 4!

When nums can contain negative numbers, both assumptions fail:

  1. Adding a negative nums[right] decreases windowSum, so stopping left early might miss a valid window that needed left to advance past a negative prefix.
  2. Removing a negative nums[left] actually increases windowSum. For example, in nums = [3, -2, 5] with target = 6, or nums = [2, -1, 2] with target = 3: in [2, -1, 2], the full array has sum = 3 >= 3 (length 3). When you shrink left = 0 (removing 2), sum drops to 1 < 3, so the while loop stops and never checks left = 2 ([2]) if target were 2! To handle negative numbers for shortest subarray with sum ≥ K, you need prefix sums combined with a monotonic deque (O(n)), not a simple two-pointer window.
Whenever a problem asks for a variable-size window based on a subarray sum or product, check the element constraints first: non-negative elements (nums[i] >= 0) for sums, or strictly positive elements (nums[i] >= 1) for products.

Next step

Check your understanding

10 quick questions