Lesson 19 · Core algorithms

Variable Size Sliding Window

When a question gives a condition instead of a width, let the window's two ends move on their own: the right end adds one value per step, and the left end drops values only until the condition is met again. Each value enters once and leaves once, so the whole scan is O(n).

Variable Size Sliding Window concept diagramShortest run with sum at least 9 in 2, 4, 1, 3, 6, 1, drawn as ten columns, one per pointer move. Each column shades the indexes inside the window after that move. The right end steps down six times and the left end four times, never back up, so the scan makes 10 moves for 6 values. The four valid windows, lengths 4, 4, 3 and 2, are green; the shortest is 3, 6 with length 2.shortest run with sum ≥ 9 · one column per pointer moveindex · value021421334651R+2R+6R+7R+10len 4L+8R+14len 4L+10len 3L+9len 2bestL+6R+7window sumrecordedleft edge 4 steps · right edge 6 steps · 10 moves ≤ 2n = 12, never back up
1

When the Width Is Not Given

A variable size sliding window answers questions about contiguous ranges where the range length is part of the answer: the shortest subarray whose sum reaches 9, the longest substring with at most two different letters. Nobody tells you the width, so the window cannot slide as a fixed block. It is also called a dynamic sliding window.

Two indexes mark the window, left and right. right moves forward one place per step and adds that value to a running summary (a sum, a letter count). left moves only when the window needs repair, and it also only moves forward. Because neither end ever goes back, no range is examined twice.

  • Brute force checks all n(n + 1)/2 ranges: O(n²) or worse
  • The window checks n right ends, and left catches up at most n times: O(n)
2

The Sliding Window Template

  1. For each right from 0 to n − 1: add a[right] to the summary.
  2. While the window needs repair: remove a[left] from the summary and move left one place.
  3. Record the answer (inside the loop for shortest, after it for longest).

Almost every problem of this kind fits one loop. Before writing it, answer two questions: what summary of the window do I keep, and what makes a window valid or invalid? The sliding window template is then the same each time:

The only part that changes between problems is the while condition and where the answer is recorded, which depends on whether you want the shortest or the longest window. Getting those two backwards is the most common bug.

3

Shortest Window: Shrink While Valid

Take 2, 4, 1, 3, 6, 1 and find the shortest run with sum at least 9. Grow: the sums are 2, 6, 7, then 10 at index 3. The window 2, 4, 1, 3 is valid, so record length 4, then try to make it shorter: drop 2, sum 8, no longer valid, stop.

Add 6: sum 14, record 4. Now the shrink runs three times in a row: drop 4 (sum 10, record 3), drop 1 (sum 9, record 2), drop 3 (sum 6, stop). The last value, 1, brings the sum to 7, which is not enough. The answer is 2, from 3 and 6.

Record inside the loop, before each removal: the window you record must still be valid. If you record after the loop, as a longest-window solution does, you record the window that just failed. Start the best length at n + 1 (or infinity) and return 0 if it never changed, or a target larger than the total sum returns nonsense.

Key reference

Terms, operations, and practical uses

Key terms

  • SummaryWhat the loop keeps about the current window: a sum, letter counts, a count of zeros.
  • RepairMoving left forward, removing values, until the window meets the condition again.
  • At most k trickCount windows with at most k, subtract those with at most k − 1, to get exactly k.
Implementation

Code in Python, C++ and Java

def shortest_at_least(nums, target):
    best = len(nums) + 1
    left = total = 0
    for right, v in enumerate(nums):
        total += v
        while total >= target:
            best = min(best, right - left + 1)
            total -= nums[left]
            left += 1
    return 0 if best > len(nums) else best


def longest_at_most_k_distinct(s, k):
    count = {}
    left = best = 0
    for right, ch in enumerate(s):
        count[ch] = count.get(ch, 0) + 1
        while len(count) > k:
            out = s[left]
            count[out] -= 1
            if count[out] == 0:
                del count[out]
            left += 1
        best = max(best, right - left + 1)
    return best


def count_at_most_k_distinct(s, k):
    count = {}
    left = total = 0
    for right, ch in enumerate(s):
        count[ch] = count.get(ch, 0) + 1
        while len(count) > k:
            out = s[left]
            count[out] -= 1
            if count[out] == 0:
                del count[out]
            left += 1
        total += right - left + 1
    return total


nums = [2, 4, 1, 3, 6, 1]
print("shortest sum >= 9:", shortest_at_least(nums, 9))
print("shortest sum >= 30:", shortest_at_least(nums, 30))
s = "abbcbca"
print("longest with <= 2 distinct:", longest_at_most_k_distinct(s, 2))
at_most_2 = count_at_most_k_distinct(s, 2)
at_most_1 = count_at_most_k_distinct(s, 1)
print("substrings with <= 2 distinct:", at_most_2)
print("substrings with exactly 2 distinct:", at_most_2 - at_most_1)
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;

int shortestAtLeast(const vector<int>& nums, int target) {
    int n = nums.size(), best = n + 1, left = 0, total = 0;
    for (int right = 0; right < n; right++) {
        total += nums[right];
        while (total >= target) {
            best = min(best, right - left + 1);
            total -= nums[left++];
        }
    }
    return best > n ? 0 : best;
}

// Returns {longest window, number of windows} with at most k distinct characters.
pair<int, long long> atMostKDistinct(const string& s, int k) {
    unordered_map<char, int> count;
    int left = 0, best = 0;
    long long total = 0;
    for (int right = 0; right < (int)s.size(); right++) {
        count[s[right]]++;
        while ((int)count.size() > k) {
            if (--count[s[left]] == 0) count.erase(s[left]);
            left++;
        }
        best = max(best, right - left + 1);
        total += right - left + 1;
    }
    return {best, total};
}

int main() {
    vector<int> nums = {2, 4, 1, 3, 6, 1};
    cout << "shortest sum >= 9: " << shortestAtLeast(nums, 9) << "\n";
    cout << "shortest sum >= 30: " << shortestAtLeast(nums, 30) << "\n";
    string s = "abbcbca";
    auto two = atMostKDistinct(s, 2), one = atMostKDistinct(s, 1);
    cout << "longest with <= 2 distinct: " << two.first << "\n";
    cout << "substrings with <= 2 distinct: " << two.second << "\n";
    cout << "substrings with exactly 2 distinct: " << two.second - one.second << "\n";
}
import java.util.HashMap;
import java.util.Map;

public class Main {
    static int shortestAtLeast(int[] nums, int target) {
        int n = nums.length, best = n + 1, left = 0, total = 0;
        for (int right = 0; right < n; right++) {
            total += nums[right];
            while (total >= target) {
                best = Math.min(best, right - left + 1);
                total -= nums[left++];
            }
        }
        return best > n ? 0 : best;
    }

    // Returns {longest window, number of windows} with at most k distinct characters.
    static long[] atMostKDistinct(String s, int k) {
        Map<Character, Integer> count = new HashMap<>();
        int left = 0, best = 0;
        long total = 0;
        for (int right = 0; right < s.length(); right++) {
            count.merge(s.charAt(right), 1, Integer::sum);
            while (count.size() > k) {
                char out = s.charAt(left++);
                if (count.merge(out, -1, Integer::sum) == 0) count.remove(out);
            }
            best = Math.max(best, right - left + 1);
            total += right - left + 1;
        }
        return new long[] {best, total};
    }

    public static void main(String[] args) {
        int[] nums = {2, 4, 1, 3, 6, 1};
        System.out.println("shortest sum >= 9: " + shortestAtLeast(nums, 9));
        System.out.println("shortest sum >= 30: " + shortestAtLeast(nums, 30));
        String s = "abbcbca";
        long[] two = atMostKDistinct(s, 2), one = atMostKDistinct(s, 1);
        System.out.println("longest with <= 2 distinct: " + two[0]);
        System.out.println("substrings with <= 2 distinct: " + two[1]);
        System.out.println("substrings with exactly 2 distinct: " + (two[1] - one[1]));
    }
}
Watch it run

Step through it

Running on [2, 4, 1, 3, 6, 1] · sum ≥ 9, then "abbcbca" · at most 2 letters

2, 4, 1, 3, 6, 1 · shortest window with sum ≥ 9all values ≥ 0204112336415brute force: 6 · 7 / 2 = 21 runs to sumlonger window → bigger sum: that is what lets left only move forward
Step 1

Shortest run with sum ≥ 9

Find the shortest run of neighbouring values whose sum is at least 9. Checking every start and end means 21 runs. The window does better because every value is ≥ 0: adding a value can only raise the sum, and dropping one can only lower it, so we always know which end to move.

Output
1 / 17
4

Longest Window: Shrink While Invalid

On the string abbcbca, find the longest substring with at most 2 different letters. Keep a count of each letter in the window. Grow until c arrives at index 3: the window abbc holds 3 letters, so drop a and stop. Grow through b and c: bbcbc, length 5, still 2 letters.

At index 6 an a arrives and the window has 3 letters again. Now left has to drop b, b, c, b, four values, before the window, ca, is valid. That long shrink is fine: those four values will never be visited again.

Remove a letter from the map when its count reaches 0. If you leave it there with count 0, the number of keys keeps saying 3 and the window shrinks for nothing.

5

Counting Windows and the Exactly k Trick

Some questions ask how many subarrays meet a condition. After the shrink, every window that ends at right and starts anywhere from left to right is valid, because a valid window stays valid when you cut values off its left side. That is right − left + 1 windows, added once per step.

For abbcbca with at most 2 letters, the additions are 1, 2, 3, 3, 4, 5, 2, a total of 20 substrings. With at most 1 letter the total is 8. Substrings with exactly 2 letters are the ones counted in the first total but not the second: 20 − 8 = 12.

"Exactly k" cannot be shrunk directly: a window with too few letters and a window with too many both fail, and the loop does not know which way to move. Two "at most" passes avoid that. See Subarrays with K Different Integers, Binary Subarrays With Sum and Count Number of Nice Subarrays.

6

Why It Is O(n), and When It Fails

The inner while makes the code look quadratic, but count moves, not loops. right moves n times. left also moves at most n times over the whole run, because it never goes back and never passes the end. In the 2, 4, 1, 3, 6, 1 example right moved 6 times and left 4 times: 10 moves, under 2n = 12. Time is O(n); space is the size of the summary, O(1) for a sum or O(alphabet) for letter counts.

The method needs one property: making the window bigger can only push the summary one way. With non-negative numbers a longer window has a larger sum, so dropping values from the left is the right repair. Negative numbers break this. For 3, −5, 4, 2 with target 6 the answer is 4, 2. The window adds 3, −5, 4, 2 and never reaches 6, so left never moves and the −5 is never dropped: it reports no answer.

With negatives, use prefix sums with a hash map for exact sums, or a monotonic queue over prefix sums for the shortest subarray reaching a target.

  • Works: non-negative sums, letter counts, distinct counts, number of zeros
  • Fails: sums with negatives, products with zeros or negatives
7

Fixed or Variable?

If the question names the length ("every substring of length k"), both ends move together and there is nothing to decide: that is a fixed size sliding window. If it names a limit and asks for the shortest, longest or how many, the width is the unknown and the window is variable. The overview of both, with the shared idea of reusing the overlap, is in sliding window, and the wider family of moving indexes in two pointers.