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 numskkknums
Example 1
Output: [3, 3, 5, 5, 6, 7]
Example 2
Output: [1]
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
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
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 inums[i]ii - k + 1ii - k
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
Writing the answers
When is there an answer to write? The first window is full once ik - 1ii - k + 1
Java Solution
The method maxSlidingWindow
- First, create the array
withresult slots, one per window, and an emptynums.length - k + 1 namedArrayDeque for the candidate indexes.dq is the JDK's deque class, built on a resizable array.ArrayDeque - Move
along the array with one loop. Eachi is the right end of a window.i - Inside the loop, look at the front index with
. If it isdq.peekFirst() or less, it has left the window, so remove it withi - k .pollFirst() - Then, while the value at the back index,
, is at mostnums[dq.peekLast()] , remove that index withnums[i] . After that, addpollLast() at the back withi .offerLast(i) - Once
is at leasti , the window is full: writek - 1 intonums[dq.peekFirst()] .result[i - k + 1] - When the loop ends, return
.result
The main[9, 8, 7, 6, 5][5, 1, 1, 1]
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:
[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][1]
Look at the third line, [9, 8, 7, 6][9, 8, 7, 6, 5]
The fourth line, [5, 1, 1]<=dq.peekFirst() < i - k[5, 5, 1][9, 9, 8, 7][7]
The original implementation,
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
orpollFirst . So all the removals in thepollLast loop, over the whole run, take at most n steps.while - Space: O(k) besides the output, because the deque only holds indexes inside the current window, at most
of them. Thek array, with one answer per window, is the output itself.result
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