Sliding Window Maximum

Find the largest number in each window of k numbers in a row as the window slides along an array.

Given an array of integers nums and a number k, picture a window that covers k numbers in a row. It starts at the left end of the array and moves one position to the right at a time, until it reaches the right end. Return the largest number in the window at each of its positions, in order. k is at least 1 and at most the length of nums.

Example 1
Input: nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
Output: [3, 3, 5, 5, 6, 7]
Example 2
Input: nums = [1], k = 1
Output: [1]
Solution

The Idea

Picture a row of number cards and a strip of paper with a hole cut in it, three cards wide. You lay the strip on the left end, read the largest number you can see through the hole, then slide the strip one card to the right and read again.

In Example 1 the hole first shows 1, 3 and -1, so the answer starts with 3. One step right it shows 3, -1 and -3: still 3. Then -1, -3 and 5 give 5, and -3, 5 and 3 give 5 again. The last two positions show 5, 3, 6 and then 3, 6, 7, giving 6 and 7. Eight cards and a hole three wide make six positions, and six answers.

Each step changes the window by just two numbers: one comes in on the right and one leaves on the left. For a sum, that would be easy: add the new number and subtract the old one. A largest number cannot be updated that way. When the window moves from 3, -1, -3 to -1, -3, 5, the 3 leaves. Knowing only that the largest number was 3 does not tell us which number is the largest now. Looking through the whole window again costs k steps at every move. Can we do better?

Look at the 5 when it arrives. The -1 and -3 to its left are still in the window, but they can never be the largest number again. They leave the window before 5 does, and while all three are inside, 5 is bigger. So we only need to remember the numbers that might still be the largest of some later window. Call them the candidates.

Look at the picture below. The top row is nums with its indexes, and the orange box marks the window over indexes 2 to 4, at the moment 5 arrives.

The array 1, 3, -1, -3, 5, 3, 6, 7 with the window over indexes 2 to 4 when 5 arrives. Before 5, the candidates from front to back are 3, -1 and -3. The 3 has left the window and -1 and -3 are smaller than 5, so all three are crossed out. After 5, the only candidate is 5, at the front: the maximum of the window.

The row labelled "candidates before 5" holds 3, -1 and -3, oldest at the front. The 3, at index 1, is crossed out because it has left the window. The -1 and -3 are crossed out because they are smaller than 5. In the row labelled "candidates after 5", only 5 is left, and it is the answer for this window.

Notice the order of the candidates before 5: 3, then -1, then -3. Each candidate is smaller than the one in front of it, because a newer, bigger number would have removed the older ones. So the candidate at the front, the oldest one still in the window, is always the largest.

The candidates are added at the back and removed from both ends: from the back when a bigger number arrives, from the front when they leave the window. A list that works at both ends like this is called a double-ended queue, or deque (said "deck"). One whose values always go down from front to back is often called a monotonic deque.

Solution Approach

Turning that idea into code means settling three things: what the deque stores, when a candidate is removed, and when to write an answer. The simple way, checking every window, shows why the candidates are worth it.

Checking every window

Why not simply look through each window for its largest number? An array of n numbers has n - k + 1 windows, and each one takes k steps. For 100,000 numbers and a window of 50,000, that is about 2.5 billion steps. With the candidates, each number joins the deque once and leaves it at most once, so the whole pass takes about 2n steps.

Storing indexes instead of values

What exactly goes into the deque? A value alone cannot tell us whether it has left the window. Example 1 has two 3s, at index 1 and at index 5. So the deque holds indexes, and the value of index i is nums[i]. The window that ends at index i covers indexes i - k + 1 to i, so an index of i - k or less is outside it.

Removing candidates from both ends

When does a candidate leave from the back? When the new number is at least as big as its value. Equal values go too: the newer copy stays in the window longer, so the older one adds nothing. Keep removing from the back until the last candidate is bigger than the new number, or the deque is empty.

And from the front? Each move pushes exactly one index out of the window, index i - k. If it is still a candidate, it is the oldest one, so it sits at the front. One check of the front at each step is enough.

Writing the answers

When is there an answer to write? The first window is full once i reaches k - 1. From then on, every step completes one window, and its largest number is the value at the front of the deque. The window that ends at i is window number i - k + 1, counting from 0, so that is where its answer goes.

Java Solution

The method maxSlidingWindow works in these steps:

  1. First, create the array result with nums.length - k + 1 slots, one per window, and an empty ArrayDeque named dq for the candidate indexes. ArrayDeque is the JDK's deque class, built on a resizable array.
  2. Move i along the array with one loop. Each i is the right end of a window.
  3. Inside the loop, look at the front index with dq.peekFirst(). If it is i - k or less, it has left the window, so remove it with pollFirst().
  4. Then, while the value at the back index, nums[dq.peekLast()], is at most nums[i], remove that index with pollLast(). After that, add i at the back with offerLast(i).
  5. Once i is at least k - 1, the window is full: write nums[dq.peekFirst()] into result[i - k + 1].
  6. When the loop ends, return result.

The main method runs both examples, a falling array [9, 8, 7, 6, 5], an array [5, 1, 1, 1] whose big first number must leave on time, and a window as wide as the whole array.

Java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

public class SlidingWindowMaximum {

    public static int[] maxSlidingWindow(int[] nums, int k) {
        int[] result = new int[nums.length - k + 1];
        Deque<Integer> dq = new ArrayDeque<>();   // indexes; their values decrease front to back
        for (int i = 0; i < nums.length; i++) {
            if (!dq.isEmpty() && dq.peekFirst() <= i - k) {
                dq.pollFirst();               // the front index has left the window
            }
            while (!dq.isEmpty() && nums[dq.peekLast()] <= nums[i]) {
                dq.pollLast();                // smaller values can never be a maximum again
            }
            dq.offerLast(i);
            if (i >= k - 1) {
                result[i - k + 1] = nums[dq.peekFirst()];   // the front is the maximum
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};
        System.out.println(Arrays.toString(maxSlidingWindow(nums, 3)));
        System.out.println(Arrays.toString(maxSlidingWindow(new int[] {1}, 1)));
        System.out.println(Arrays.toString(maxSlidingWindow(new int[] {9, 8, 7, 6, 5}, 2)));
        System.out.println(Arrays.toString(maxSlidingWindow(new int[] {5, 1, 1, 1}, 2)));
        System.out.println(Arrays.toString(maxSlidingWindow(new int[] {2, 7, 4}, 3)));
    }
}

Running it prints:

Output
[3, 3, 5, 5, 6, 7]
[1]
[9, 8, 7, 6]
[5, 1, 1]
[7]

The answers for Example 1, [3, 3, 5, 5, 6, 7], match the six windows read through the paper strip, and [1] is the single window of Example 2.

Look at the third line, [9, 8, 7, 6]. In the falling array [9, 8, 7, 6, 5], no candidate is ever removed from the back, because each new number is smaller. Instead the front leaves at every step: 9 goes when 7 arrives, and 8 goes when 6 arrives.

The fourth line, [5, 1, 1], shows why the front check uses <=. The 5 at index 0 must go as soon as the window covers indexes 1 and 2. With dq.peekFirst() < i - k instead, it stays one step too long, and that line prints [5, 5, 1]. With that same change, the falling array prints [9, 9, 8, 7]. The last line, [7], comes from a window as wide as the array: one window, one answer.

The original implementation, SlidingWindowMaximum.java, is on GitHub.

Complexity

Every index enters the deque exactly once, so the work is limited by how often indexes can leave it.

  • Time: O(n), because the loop visits each of the n indexes once, and each index is removed at most once, by pollFirst or pollLast. So all the removals in the while loop, over the whole run, take at most n steps.
  • Space: O(k) besides the output, because the deque only holds indexes inside the current window, at most k of them. The result array, with one answer per window, is the output itself.

A max-heap, a structure that always hands out its largest value, also works: remove an index from it only when it reaches the top after leaving the window. That takes O(n log n) time. For the middle value of each window instead of the largest, see Sliding Window Median.