Sliding Window Basics

How a window that slides along an array answers questions about runs of neighbouring numbers in one pass.

Picture a paper frame laid over a row of numbers, showing only a few of them at a time. You slide it along the row, and at every stop you only need to look at what came in and what went out. A sliding window does exactly that in code. It answers questions about neighbouring items of an array or string, such as the largest sum of three numbers in a row.

Runs of neighbouring numbers

All the examples use the same six numbers, nums = [2, 3, 1, 2, 4, 3]. A run here means numbers that sit next to each other with no gaps. The numbers 3, 1, 2 form a run. The numbers 3, 2, 3 do not, because they skip the 1 and the 4 between them. Books call such a run a subarray, or a substring when the input is text, and the word contiguous means "with no gaps".

Four questions about runs come up again and again. Here they are for those six numbers:

  • Which run of exactly 3 numbers has the largest sum?
  • What is the shortest run with a sum of at least 7?
  • What is the longest run with a sum of at most 7?
  • How many runs have a sum of at least 7?

A window is the run you are looking at right now. Two indexes describe it: left, the position of its first number, and right, the position of its last. The window with left = 1 and right = 3 holds 3, 1, 2. It has right - left + 1 = 3 numbers.

Checking every run

Why not simply try every run? Two loops do it, one inside the other. The outer loop picks the first index, and the inner loop moves the last index forward one step at a time, adding each new number to a sum. For our six numbers that makes 21 runs, and finding the shortest run with a sum of at least 7 this way means checking all 21. For n numbers there are n(n + 1)/2 runs, so doubling the array roughly quadruples the work.

Most of that work is repeated: the runs 3, 1, 2 and 1, 2, 4 share the 1 and the 2, yet each adds them up again. A sliding window keeps the sum of the current window and changes it only by the numbers that enter or leave. Each number enters the window once and leaves it at most once, so a single pass over the array is enough.

Fixed-size windows

Which 3 numbers in a row have the largest sum? Every candidate has the same length, so the window keeps a fixed size, called k. Here k = 3, and the window takes four positions along the six numbers:

A window of 3 slides over 2, 3, 1, 2, 4, 3. Its sums are 6, 6, 7 and 9, and window 4, holding 2, 4, 3, has the largest sum.

The row labelled window 1 holds 2, 3, 1, with sum 6. To reach window 2, the 2 at index 3 enters on the right and the 2 at index 0 leaves on the left. The new sum is 6 + 2 - 2 = 6, found with one addition and one subtraction instead of three additions.

The same step gives window 3 (6 + 4 - 3 = 7) and window 4 (7 + 3 - 1 = 9). Window 4, drawn in orange, holds 2, 4, 3 and has the largest sum, 9.

In code, one loop moves the window's right edge along the array, with the index right. At every step nums[right] enters. Once right reaches k, the number nums[right - k] leaves, which keeps the window at k numbers. From right = k - 1 on, the window is full and its sum can be compared with the best so far.

Variable-size windows: the shortest run

What is the shortest run with a sum of at least 7? Now the length is the answer, so the window has to stretch and shrink. While the sum is too small, right moves forward to take in one more number. While the sum is at least 7, the window is valid: record its length, then move left forward to drop its first number and try a shorter window.

The windows visited while looking for the shortest run with sum at least 7 in 2, 3, 1, 2, 4, 3. Blue windows are too small and grow, teal windows are valid and shrink, and the orange window 4, 3 is the shortest.

Follow the rows of the picture from the top. The window 2, 3, 1 has sum 6, marked "too small: grow", so it takes in the 2 at index 3. The sum is now 8, so length 4 is recorded and the 2 at index 0 leaves. The window 3, 1, 2 is too small again and grows to take in the 4.

The blue rows are too small and grow. The teal rows are valid, and each is recorded before it shrinks. The orange row, 4, 3 with sum 7, is the shortest of them, with length 2. After it, the window is down to the last 3, with sum 3 and no numbers left to take in.

Why is it safe to drop the 2 at index 0 for good? Length 4 has already been recorded for the window that starts there. Any later window starting at index 0 would be longer than 4, so none of them can be the shortest. The same reasoning holds at every step, so left never has to move back.

Variable-size windows: the longest run

What about the longest run with a sum of at most 7? The steps are the same as for the shortest run, in a different order. First grow by one number. If the sum is now above 7, the window is broken, so drop numbers from the left until the sum is at most 7 again. Only then is the window valid, so its length is recorded after the shrinking, not during it.

On our six numbers, the window grows to 2, 3, 1 with sum 6. Adding the 2 at index 3 makes 8, so the first 2 leaves and the window is 3, 1, 2. Adding the 4 makes 10, so the 3 leaves and the window is 1, 2, 4, with sum exactly 7. Adding the last 3 makes 10 again, and this time two numbers, 1 and 2, leave before the window 4, 3 is valid. Three windows reached length 3, and none was longer, so the answer is 3.

So the shortest-run and longest-run windows differ in where the length is recorded. For the shortest run, the window is valid while it shrinks. For the longest run, it is valid only once the shrinking has finished.

Counting runs with a window

How many runs have a sum of at least 7? A window can count them in groups, using the shrinking rule from the shortest run: after taking in nums[right], drop numbers from the left while the sum is at least 7. When the shrinking stops, the window from left to right is too small, but the window one number longer, starting at left - 1, was valid (if left has moved at all).

When right is 4, the window has shrunk to 2, 4 with left = 3. Runs that start at index 0, 1 or 2 and end at index 4 have a sum of at least 7, so 3 is added to the count.

The picture is taken when right = 4. The window, in blue, has shrunk to 2, 4 with sum 6, and left = 3. The orange cells are the valid starts 0, 1 and 2. Starting at any of them and ending at index 4 gives a sum of 12, 10 or 7, all at least 7. Because every number is positive, starting further left only makes the sum bigger.

So left itself is the number of valid runs that end at right, and the count grows by left at each step. Over the six values of right it grows by 0, 0, 0, 1, 3 and 5, a total of 9. Listing every run with two loops also finds 9.

The templates in Java

The program below has one method per question, plus the slow way for comparison:

  • Fixed size: maxSumOfK, which rejects a k below 1 or longer than the array.
  • Shortest run: shortestWithSumAtLeast, which records inside the shrinking loop and returns 0 when no run reaches the target.
  • Longest run: longestWithSumAtMost, which records after the shrinking loop.
  • Counting: countWithSumAtLeast, which adds left after the shrinking loop.
  • Slow way: bruteShortest, which returns the shortest length and how many runs it checked.

The main method asks the four questions about [2, 3, 1, 2, 4, 3]. Then it tries a target no run reaches, a limit no number fits under, windows of 6 and 7, huge values and a negative number. Every running sum is a long rather than an int, for a reason the huge values show.

Java
public class SlidingWindowBasics {

    // Fixed size: the largest sum of any k elements in a row.
    static long maxSumOfK(int[] nums, int k) {
        if (k <= 0 || k > nums.length) {
            throw new IllegalArgumentException("k must be between 1 and " + nums.length);
        }
        long sum = 0;
        long best = Long.MIN_VALUE;
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];                  // nums[right] enters the window
            if (right >= k) {
                sum -= nums[right - k];          // nums[right - k] leaves it
            }
            if (right >= k - 1) {
                best = Math.max(best, sum);      // the window holds exactly k elements
            }
        }
        return best;
    }

    // Variable size, shortest: length of the shortest run with sum >= target, 0 if none.
    static int shortestWithSumAtLeast(int[] nums, int target) {
        int left = 0;
        long sum = 0;
        int best = Integer.MAX_VALUE;
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];                  // grow
            while (sum >= target) {              // valid: record, then try a shorter one
                best = Math.min(best, right - left + 1);
                sum -= nums[left];
                left++;
            }
        }
        return best == Integer.MAX_VALUE ? 0 : best;
    }

    // Variable size, longest: length of the longest run with sum <= limit.
    static int longestWithSumAtMost(int[] nums, int limit) {
        int left = 0;
        long sum = 0;
        int best = 0;
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];                  // grow
            while (sum > limit) {                // broken: shrink until valid again
                sum -= nums[left];
                left++;
            }
            best = Math.max(best, right - left + 1);
        }
        return best;
    }

    // Counting: how many runs have sum >= target.
    static long countWithSumAtLeast(int[] nums, int target) {
        int left = 0;
        long sum = 0;
        long count = 0;
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (sum >= target) {
                sum -= nums[left];
                left++;
            }
            count += left;                       // starts 0 .. left - 1 all work
        }
        return count;
    }

    // The slow way: try every start and every end.
    static int[] bruteShortest(int[] nums, int target) {
        int best = Integer.MAX_VALUE;
        int checked = 0;
        for (int start = 0; start < nums.length; start++) {
            long sum = 0;
            for (int end = start; end < nums.length; end++) {
                sum += nums[end];
                checked++;
                if (sum >= target) {
                    best = Math.min(best, end - start + 1);
                }
            }
        }
        return new int[] {best == Integer.MAX_VALUE ? 0 : best, checked};
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 2, 4, 3};
        System.out.println("Largest sum of 3 in a row: " + maxSumOfK(nums, 3));
        System.out.println("Shortest with sum >= 7: " + shortestWithSumAtLeast(nums, 7));
        System.out.println("Longest with sum <= 7: " + longestWithSumAtMost(nums, 7));
        System.out.println("Runs with sum >= 7: " + countWithSumAtLeast(nums, 7));
        int[] slow = bruteShortest(nums, 7);
        System.out.println("Slow way: shortest " + slow[0] + ", runs checked " + slow[1]);

        System.out.println("Shortest with sum >= 100: " + shortestWithSumAtLeast(nums, 100));
        System.out.println("Longest with sum <= 0: " + longestWithSumAtMost(nums, 0));
        System.out.println("Largest sum of 6 in a row: " + maxSumOfK(nums, 6));
        try {
            maxSumOfK(nums, 7);
        } catch (IllegalArgumentException e) {
            System.out.println("Largest sum of 7 in a row: " + e.getMessage());
        }

        int[] big = {2000000000, 1000000000, 500000000};
        System.out.println("Largest sum of 2 in a row, big values: " + maxSumOfK(big, 2));

        int[] withNegative = {1, -1, 5};
        System.out.println("With a negative number, window says: "
                + shortestWithSumAtLeast(withNegative, 5));
        System.out.println("With a negative number, slow way says: "
                + bruteShortest(withNegative, 5)[0]);
    }
}

Running it prints:

Output
Largest sum of 3 in a row: 9
Shortest with sum >= 7: 2
Longest with sum <= 7: 3
Runs with sum >= 7: 9
Slow way: shortest 2, runs checked 21
Shortest with sum >= 100: 0
Longest with sum <= 0: 0
Largest sum of 6 in a row: 15
Largest sum of 7 in a row: k must be between 1 and 6
Largest sum of 2 in a row, big values: 3000000000
With a negative number, window says: 3
With a negative number, slow way says: 1

The first four lines answer the four questions with 9, 2, 3 and 9 runs, the same numbers the windows gave when followed by hand. The fifth line shows the slow way agreeing on length 2, after checking all 21 runs.

The line Shortest with sum >= 100: 0 is how the method reports that no run reaches 100. The whole array only adds up to 15, which is what the window of 6 reports two lines later. The longest run with a sum of at most 0 has length 0, because each number makes the sum positive and the shrinking loop removes it straight away. A window of 7 does not fit in six numbers, and the method says so instead of returning a made-up sum.

Where a window goes wrong

A sliding window is only right when its condition has a direction: adding a number always pushes the sum one way, and removing it always pushes it back. The last three output lines come from two inputs that trip a window up.

Negative numbers

In [1, -1, 5], the shortest run with a sum of at least 5 is the 5 on its own, length 1. The window says 3 and the slow way says 1. Follow the window: the sum is 1, then 0, then 5 when the 5 arrives. The window 1, -1, 5 is valid, so length 3 is recorded and the 1 leaves. The sum drops to 4 and the shrinking stops, so the window never tries dropping the -1 as well, which would bring the sum back to 5.

With a negative number in the array, a shorter window can have a larger sum, so stopping the shrinking early is no longer safe. Such problems need a different tool, for example running totals from index 0 (prefix sums) kept in a map, as in Subarray Sum Equals K.

Sums too large for an int

In [2000000000, 1000000000, 500000000] with k = 2, the first two numbers add up to 3,000,000,000, and the program prints that. An int stops at 2,147,483,647, so a version of the same loop with an int sum gets this wrong. Run separately, that version computes the first window's sum as -1,294,967,296, because the addition wraps around past the largest int. The second window comes out as 1,500,000,000, and that is what it returns as the largest sum.

Spotting a sliding window problem

How do you tell that a new problem fits a window? Three signs together point to one:

  • The question is about runs: words such as subarray, substring, "in a row" or "consecutive".
  • It asks for the largest, smallest, shortest or longest such run, or how many there are.
  • The condition has a direction: adding an item pushes it one way, and removing the item pushes it back. Sums of positive numbers work, and so do the number of different letters in a piece of text, the number of zeros in a run, and letter counts compared with a target.

When the third sign is missing, a twist sometimes brings it back: run the window several times, each time fixing one extra value such as how many different letters the window may hold. The window's left and right are two indexes that both move forward through the array, so the whole technique is a special case of two pointers.

Complexity

Each template makes one pass, and the slow way does not.

  • Time: O(n) for every template, because right visits each of the n numbers once and left only moves forward, at most n steps in all.
  • Time of the slow way: O(n2), because its two loops check all n(n + 1)/2 runs, 21 of them for our six numbers.
  • Space: O(1) for the templates here, because they keep only left, right, the sum and the answer.

A window that must remember which letters or values it holds needs a map, a set or a deque for them, and that takes space for the items inside the window.

Where to go next

Fixed-size windows:

Variable-size windows, shortest run:

Variable-size windows, longest run:

Counting and twists: