Tech Interview RoomStudy guides

Sliding Window

Minimum size subarray with sum ≥ target (variable sliding window). Compare brute force, binary search and two pointers.

Intermediate · 2 min read · Lesson 3 of 5 in Sliding Window

Problem

Positive integers nums and a target: return the length of the shortest contiguous subarray whose sum is at least the target, or 0. target = 7, nums = [2, 3, 1, 2, 4, 3] → 2 ([4, 3]).

Pattern

Variable-size sliding window: expand right until the window is valid, then shrink left while it stays valid, recording the best. Works when adding elements moves the condition in one direction (here, all numbers are positive).

Approach 1: Every start, extend until valid (feasible, O(n²))

java
class MinWindowBrute {
    static int minLen(int target, int[] a) {
        int best = Integer.MAX_VALUE;
        for (int i = 0; i < a.length; i++) {
            int sum = 0;
            for (int j = i; j < a.length; j++) {
                sum += a[j];
                if (sum >= target) { best = Math.min(best, j - i + 1); break; }
            }
        }
        return best == Integer.MAX_VALUE ? 0 : best;
    }
}

Approach 2: Prefix sums + binary search (O(n log n))

Prefix sums of positive numbers are increasing, so for each start you can binary-search the first end reaching the target.

java
import java.util.Arrays;

class MinWindowBinarySearch {
    static int minLen(int target, int[] a) {
        int n = a.length;
        int[] prefix = new int[n + 1];
        for (int i = 0; i < n; i++) prefix[i + 1] = prefix[i] + a[i];
        int best = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            int need = prefix[i] + target;
            int pos = Arrays.binarySearch(prefix, i + 1, n + 1, need);
            if (pos < 0) pos = -(pos + 1);                       // first prefix >= need
            if (pos <= n) best = Math.min(best, pos - i);
        }
        return best == Integer.MAX_VALUE ? 0 : best;
    }
}

Approach 3: Shrinkable sliding window (O(n)) — optimal

java
class MinWindowSliding {
    static int minLen(int target, int[] a) {
        int left = 0, sum = 0, best = Integer.MAX_VALUE;
        for (int right = 0; right < a.length; right++) {
            sum += a[right];
            while (sum >= target) {                              // valid: try to shrink
                best = Math.min(best, right - left + 1);
                sum -= a[left++];
            }
        }
        return best == Integer.MAX_VALUE ? 0 : best;
    }
}

class MinWindowDemo {
    public static void main(String[] args) {
        int[] a = {2, 3, 1, 2, 4, 3};
        System.out.println(MinWindowBrute.minLen(7, a) + " " + MinWindowBinarySearch.minLen(7, a) + " " + MinWindowSliding.minLen(7, a));   // 2 2 2
        System.out.println(MinWindowSliding.minLen(100, a));   // 0
    }
}

Feasible → optimal

O(n²) → O(n log n) with prefix sums and binary search → O(n): each index enters and leaves the window at most once. If negative numbers were allowed, the window would not work; use prefix sums with a monotonic deque instead.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): longest substring with at most K distinct characters.

Expand right adding characters to a frequency map; while the map has more than K keys, shrink from the left decrementing counts (removing at zero). Track the maximum length. O(n).

Related (same pattern): max consecutive ones if you can flip at most K zeros.

Window that contains at most K zeros: expand, count zeros, shrink while zeros > K, track the maximum window length. O(n). The same template solves "longest repeating character replacement" (window length minus count of the most frequent character must be ≤ K).