Variable-size windows
26 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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)); }}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, thenwhile (window is invalid)shrinkleft++, and finally recordmaxLen = Math.max(maxLen, right - left + 1)once the window is valid. - Shortest valid window (e.g., sum ≥ target): expand
right, thenwhile (window is valid)recordminLen = Math.min(minLen, right - left + 1)inside thewhileloop and shrinkleft++to see if an even shorter window ending atrightis 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.
- Initialize left = 0, windowSum = 0, and minLen = Integer.MAX_VALUE.
- For each right from 0 to nums.length - 1, add nums[right] to windowSum.
- While windowSum >= target: update minLen = Math.min(minLen, right - left + 1), subtract nums[left] from windowSum, and increment left.
- Return minLen == Integer.MAX_VALUE ? 0 : minLen.
Shortest Subarray With Sum ≥ 7 on nums = [2, 3, 1, 2, 4, 3]
Step 1 of 6
- sum
- 6
- target
- 7
- minLen
- INF
Example 2 · Brute force: try every start and end (O(n²) time, O(1) space)
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)); }}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
leftmove forward without ever going back.
Example 3 · Optimal: grow on the right, shrink on the left (O(n) time, O(1) space)
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)); }}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:
leftandrightonly 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]reachessum = 8 >= 7. Inside thewhile (sum >= 7)loop, we record length4, subtractnums[0] = 2(left = 1,sum = 6 < 7).right = 4: add4(sum = 10 >= 7). Record length4([3, 1, 2, 4]), subtract3(left = 2,sum = 7 >= 7). Still valid! Record length3([1, 2, 4]), subtract1(left = 3,sum = 6 < 7).right = 5: add3(sum = 9 >= 7). Record length3([2, 4, 3]), subtract2(left = 4,sum = 7 >= 7). Still valid! Record length2([4, 3]), subtract4(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
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)); }}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:
- Adding a negative
nums[right]decreaseswindowSum, so stoppingleftearly might miss a valid window that neededleftto advance past a negative prefix. - Removing a negative
nums[left]actually increaseswindowSum. For example, innums = [3, -2, 5]withtarget = 6, ornums = [2, -1, 2]withtarget = 3: in[2, -1, 2], the full array hassum = 3 >= 3(length 3). When you shrinkleft = 0(removing2),sumdrops to1 < 3, so thewhileloop stops and never checksleft = 2([2]) iftargetwere2! 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.
Next step
Check your understanding
10 quick questions