Arrays & Hashing · Pattern 12 of 26

Sliding window of a variable size

Grow the window on the right; when it breaks the rule, shrink it from the left until it is valid again. Both ends only move forward, so it is O(n).

4 variations · 15 problems · 5 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Longest or shortest subarray / substring that satisfies a condition
  • The condition only gets worse as the window grows (more distinct letters, bigger sum with positive numbers)
  • Count subarrays where every smaller window is also valid

The template

Sliding Window · Variable
// longest substring without repeating characters: shrink while invalid
int lengthOfLongestSubstring(String s) {
    Map<Character, Integer> count = new HashMap<>();
    int best = 0;
    for (int l = 0, r = 0; r < s.length(); r++) {
        char c = s.charAt(r);
        count.merge(c, 1, Integer::sum);                 // grow on the right
        while (count.get(c) > 1) {                       // invalid: shrink from the left
            count.merge(s.charAt(l++), -1, Integer::sum);
        }
        best = Math.max(best, r - l + 1);
    }
    return best;
}

// shortest subarray with sum >= target (positive numbers): shrink while valid
int minSubArrayLen(int target, int[] nums) {
    int best = Integer.MAX_VALUE, sum = 0;
    for (int l = 0, r = 0; r < nums.length; r++) {
        sum += nums[r];
        while (sum >= target) { best = Math.min(best, r - l + 1); sum -= nums[l++]; }
    }
    return best == Integer.MAX_VALUE ? 0 : best;
}

The variations

  1. 1Longest window that stays valid

    Grow, then shrink only until valid again, then record the length. For "at most k replacements", the window is valid while length − most frequent count ≤ k.

  2. 2Shortest window that becomes valid

    Grow until valid, then shrink while it stays valid, recording the length at every step.

  3. 3Count the windows

    If every sub-window of a valid window is valid, each right end adds r − l + 1 subarrays. For exact conditions, use atMost(k) − atMost(k − 1) or track the last bad index.

  4. 4More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Using a sliding window when numbers can be negative: shrinking no longer makes the sum smaller. Use prefix sums.
  • Recording the answer inside the shrink loop for "longest" (it belongs after) or outside it for "shortest" (it belongs inside).
  • Counting subarrays: add r − l + 1 for every r, the number of valid windows ending at r.
Next: Sliding window with a hash map →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.