Quick revision
The short answer
The maximum of every window of k elements is a sliding window problem solved with a monotonic deque. We keep the indexes of the useful candidates in a deque whose values fall from front to back: each new element pops the smaller values from the back, the front is dropped once it leaves the window, and the front is always the window's maximum. Each index enters and leaves once, so it is O(n) time and O(k) extra space.
The solution
What it costs
| Approach | Time | Extra space |
|---|---|---|
| Rescan every window | O(n x k) | O(1) |
| Max-heap of value and index, lazy deletion | O(n log n) | O(n) |
| Monotonic deque of indexes | O(n) | O(k) |
What to remember
We found the maximum of every window of k numbers with a monotonic deque of indexes. A new number pops every smaller or equal number from the back, because those can never be the tallest hill in view again; the front leaves once its index falls out of the window; and the front is always the current maximum. Each index enters and leaves once, so the work is O(n) time and O(k) space, against O(n x k) for rescanning. The clue to remember is a fixed-size window whose summary cannot be updated by subtraction, such as a maximum: keep a deque of the candidates that could still win.
1What the question asks, seen through a train window
Imagine sitting in a train that passes a long range of hills. The window is just wide enough to show three hills at a time, and every time the train moves on by one hill, you are asked which hill in view is the tallest. The hills are the numbers in our array, the window is a run of k consecutive numbers, and the question asks for the tallest one in every position of the window, from the left end of the range to the right.
Let us keep one example for the whole article: the array [1, 3, -1, -3, 5, 3, 6, 7] with k = 3. The first window shows 1, 3 and -1, so its maximum is 3. Slide one step and we see 3, -1 and -3, maximum 3. Then -1, -3 and 5, maximum 5; then -3, 5 and 3, maximum 5; then 5, 3 and 6, maximum 6; and finally 3, 6 and 7, maximum 7. The answer is [3, 3, 5, 5, 6, 7]. An array of n numbers has n - k + 1 windows, here 8 - 3 + 1 = 6.
Each row is the same array with one window in view. The marked cell in each row is that window's maximum.
1Row by row the window slides one step right. The maxima read down the rows are 3, 3, 5, 5, 6 and 7, which is the answer.
What to assume
- Can k be larger than the array?
- We assume 1 <= k <= n and return an empty result otherwise, since no full window exists.
- Can values be negative or repeated?
- Yes to both, as the example shows.
- Do we return values or positions?
- Values, as an int array.
- How large is the input?
- Up to about 100,000 numbers, with k up to n, so anything costing n x k steps, which can reach billions, is too slow.
A careful candidate asks a few questions. Can k be larger than the array? We assume 1 <= k <= n and return an empty result otherwise, since no full window exists. Can values be negative or repeated? Yes to both, as the example shows. Do we return values or positions? Values, as an int array. How large is the input? Up to about 100,000 numbers, with k up to n, so anything costing n x k steps, which can reach billions, is too slow.
The problem is smaller than it looks. We need no clever mathematics, only a way to stop looking at the same hills again and again, and the key idea will come from the train window.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to spot the pattern behind a moving window
On a first reading, the natural plan is to take each window and find its largest number, which we will try next. A beginner who has met sliding windows may also try to keep a running maximum and update it as the window moves. That works for a sum, where we add the number entering and subtract the number leaving. It breaks for a maximum: when the 3 leaves the window [3, -1, -3], what is the new maximum? Nothing we stored tells us.
So let us read the clues one at a time. The first is the phrase k consecutive elements. Consecutive means the numbers sit side by side with no gaps, and a fixed k means every window has the same length. That is the sign of a sliding window, a frame of fixed width that moves one step at a time, so that each step adds one number on the right and drops one on the left.
The second clue is the word maximum. A maximum is not something we can undo by subtraction, so the window needs to remember more than one number: it needs to remember who would take over if the current maximum left. Those are the numbers still worth watching, and old ones must leave from one end while new ones join at the other.
Those clues point to the sliding window pattern, with a helper called a monotonic deque. A deque, short for double-ended queue and pronounced deck, is a line of items that can be joined or left at either end. Monotonic means its values only ever go one way, here falling from front to back. The general rule to carry away is this: when a fixed-size window needs a summary that cannot be updated by adding and subtracting, such as a maximum or a minimum, keep a deque of the candidates that could still become the answer.
Two patterns look similar. A monotonic stack, used for the next greater element, also pops smaller values, but items leave it from one end only, while our window also loses old items at the front. A heap, a structure that always gives its largest item quickly, looks perfect, but it cannot cheaply remove a number from its middle when that number leaves the window, so it becomes our middle step rather than the answer.
3The honest first attempt, rescanning every window
The brute force is what we did by hand. For each window, we start with its first number and compare it with each of the others, keeping the largest. It is correct, short and easy to trust, which is exactly what a first attempt should be.
Let us count on the example. There are six windows of three numbers, so we look at 18 numbers and make two comparisons per window, 12 in all. For n numbers and windows of k, there are n - k + 1 windows and each costs about k steps, so the time is O(n x k), read as order n times k. With n = 100,000 and k = 50,000 that is about 2.5 billion steps. The extra space, beyond the result, is O(1), meaning a fixed amount.
Where is the waste? Two neighbouring windows share k - 1 numbers, so we compare the same numbers again and again. Worse, we keep comparing numbers that can never win. Look at the window [-1, -3, 5]. Once the 5 has arrived, the -1 and -3 are finished, because every later window that still contains them also contains the 5, and they will leave before it does. The brute force does not know this, so it keeps looking at them.
4Getting to the deque of useful candidates, one observation at a time
A sensible middle step keeps the window's numbers in a heap of pairs, each pair a value and its index, with the largest value on top. When the top's index has fallen out of the window, we throw it away and look again, a trick called lazy deletion. That brings the time down to O(n log n), but the heap still keeps useless small numbers around. So let us use the observation we just found.
Back to the train. When a tall hill comes into view, every smaller hill already in the window will slide out of view before it, because those hills came in earlier. While the tall hill is in view, they can never be the tallest. So we may forget them for good. The same is true in the array: when a[i] arrives, every earlier number in the window that is smaller than or equal to it is useless from now on.
What is left after we forget them? Only numbers that are larger than everything that came after them. Read from oldest to newest, their values fall, which is why we call the deque monotonic. When a new number arrives, we look at the back of the deque, where the newest candidates are, and pop every one that is not larger than the new number, then put the new one at the back. The front is then the oldest survivor, larger than everything behind it, so it is the maximum of the window.
Now the question a beginner asks. Why do we store indexes in the deque and not the values themselves? Let us try values and see what we lose. At i = 4 the window moves to indexes 2 to 4, and the 3 at index 1 must leave. If the deque held only the value 3, we could not tell whether that 3 is the old one at index 1 or a newer 3 still in the window. An index tells us its age, so we can check whether it is too old.
That check is the last piece. The window ending at i covers indexes i - k + 1 to i, so an index of i - k or less has left it. Because the deque is kept in index order, only the front can be that old, so at each step we look at the front alone and remove it if dq.peekFirst() <= i - k. The whole step is therefore drop the expired front, pop smaller values from the back, push i, and once i >= k - 1, read the front.
Why is the front always right? Every number in the window that is missing from the deque was popped by a larger or equal number that came later and is still in the window, so the window's maximum is never thrown away. Among the numbers that stayed, values fall from front to back, so the largest is at the front.
Why is it fast, when a single step may pop several numbers? Count each index's life instead of each step. Every index is pushed once and popped at most once, from one end or the other. Over the whole array that is at most n pushes and n pops, so the total is O(n), even though one step, like i = 6, may pop two numbers.
The mistake beginners make most often is reading the answer too early. The deque has a front from the very first step, so it is tempting to write a result at i = 0. But the first full window ends at i = k - 1, and the window that ends at i starts at i - k + 1, which is why the result index is i - k + 1.
5Watching the deque on 1, 3, -1, -3, 5, 3, 6, 7
The picture runs the loop on our example with k = 3. Faded cells lie outside the current window. Marked cells are the indexes still in the deque, the cell under i is the number arriving, and once a window is full the front is marked as its maximum. The panel shows the deque front first, each value with its index, and the result so far.
Step i = 4 is split into two frames, because two different things happen there: the front leaves because it is too old, and then the new number pops the small values from the back.
Faded cells are outside the window. Marked cells are the indexes still in the deque; the front, once a window is full, is that window's maximum.
- window
- 0..0
- deque
- 1 (i0)
- result
- []
1i = 0 brings in 1. The deque is empty, so index 0 simply joins at the back. The first window is not full yet, so nothing is reported.
- window
- 0..1
- deque
- 3 (i1)
- result
- []
2i = 1 brings in 3. The back holds 1, and 1 <= 3, so index 0 is popped: 1 can never be a maximum while 3 is in the window. Then index 1 joins.
- window
- 0..2
- deque
- 3 (i1), -1 (i2)
- result
- [3]
3i = 2 brings in -1, which is smaller than 3, so nothing is popped and index 2 joins behind. The first window is full, and its maximum is the front, 3.
- window
- 1..3
- deque
- 3 (i1), -1 (i2), -3 (i3)
- result
- [3,3]
4i = 3 brings in -3. The front, index 1, is still inside the window 1..3, nothing is smaller than -3, so it joins. The front 3 is again the maximum.
- window
- 2..4
- deque
- -1 (i2), -3 (i3)
- result
- [3,3]
5i = 4. The window is now 2..4, and the front, index 1, is i - k = 1, so it has left the window and is removed from the front.
- window
- 2..4
- deque
- 5 (i4)
- result
- [3,3,5]
6Then 5 pops -3 and -1 from the back, since neither can ever be a maximum again, and joins. The deque holds only 5, the maximum of -1, -3, 5.
- window
- 3..5
- deque
- 5 (i4), 3 (i5)
- result
- [3,3,5,5]
7i = 5 brings in 3, smaller than 5, so it waits behind 5 in case 5 leaves first. The maximum of -3, 5, 3 is the front, 5.
- window
- 4..6
- deque
- 6 (i6)
- result
- [3,3,5,5,6]
8i = 6 brings in 6, which pops 3 and then 5 from the back. The deque holds only 6, and the maximum of 5, 3, 6 is 6.
- window
- 5..7
- deque
- 7 (i7)
- result
- [3,3,5,5,6,7]
9i = 7 brings in 7, which pops 6. The last window is 3, 6, 7, its maximum is 7, and the result is complete.
Let us read the important frames back. At i = 1 the 3 pops the 1, the train window idea at work. At i = 2 and i = 3 the new numbers are small, so they wait behind the 3, falling from front to back, in case the 3 leaves first.
At i = 4 both kinds of removal happen. The 3 at index 1 is exactly i - k = 1, so it has left and goes from the front. Then the 5 pops -3 and -1 from the back. Notice the order in the code: expiry first, then popping, then pushing.
From i = 5 onwards the pattern repeats. The 3 at index 5 waits behind the 5; then the 6 pops both, and the 7 pops the 6. The results collected are 3, 3, 5, 5, 6 and 7, matching the six windows we worked out by hand.
6The complete Java program
Here is the full program. It uses an ArrayDeque of indexes, Java's ordinary double-ended queue. main runs the example, the window size 1, a window as long as the array, and an empty array, and each comment shows what that line prints.
Let us read maxSlidingWindow in the order it runs. The first line guards the impossible cases: if k is not positive or longer than the array, no full window exists and we return an empty array. Then we make the result array with one place per window, n - k + 1, and an empty deque.
Inside the loop, the first if looks at the front. If its index is i - k or less, it has slid out of the window, so pollFirst removes it. One check is enough, because the window moves by one each step and at most one index can expire.
The while loop looks at the back. As long as the value at the back index is less than or equal to a[i], that candidate can never be a maximum again, so pollLast removes it. Then offerLast(i) puts the new index at the back. Popping equal values is safe, because the newer copy stays in the window at least as long as the older one.
Finally, once i has reached k - 1, the window ending at i is full, and we store a[dq.peekFirst()], the value at the front index, in result[i - k + 1]. After the loop, result holds one maximum per window.
7How much it costs, and the cases at the edges
Let us count on the example first. Eight indexes were pushed. Six were popped from the back, one at i = 1, two at i = 4, two at i = 6 and one at i = 7, and one was removed from the front, at i = 4. That is 15 deque operations for 8 numbers, below the limit of 2n = 16. In general every index is pushed once and popped at most once, so the time is O(n), whatever k is.
The deque never holds more than k indexes, because anything older than the window is removed from the front, so the extra space is O(k), besides the result array of n - k + 1 numbers.
| Approach | Time | Extra space |
|---|---|---|
| Rescan every window | O(n x k) | O(1) |
| Max-heap of value and index, lazy deletion | O(n log n) | O(n) |
| Monotonic deque of indexes | O(n) | O(k) |
The edge cases need no extra code. With k = 1 every window is a single number; at each step the previous index expires from the front, the deque holds only i, and the result equals the input. With k equal to the array length there is one window, and its answer is the largest number, 9 for [9, 8, 7]. Repeated values are handled by popping equal values from the back. An empty array, or a k larger than the array, returns an empty result from the guard on the first line.
A falling array such as [9, 8, 7, 6] with k = 2 is worth tracing by hand. Nothing is popped from the back, so the deque fills to its largest size, k, and the front simply expires one index at a time, giving [9, 8, 7].
8Follow-up questions
How would you find the minimum of every window instead?
We flip the comparison and keep everything else. The deque now keeps values rising from front to back, so when a new number arrives we pop from the back every value that is greater than or equal to it, because a larger, older number can never be the minimum while the smaller newer one is in view. The front is then the window's minimum. Some problems need both at once, such as the longest subarray whose largest and smallest values differ by at most a limit, and they simply keep two deques side by side.
Can it be done without a deque?
Yes, with a block method. Cut the array into blocks of k numbers. For each position, compute the maximum from the start of its block up to it, and the maximum from it to the end of its block, in two simple passes. A window starting at i covers the end of one block and the start of the next, so its maximum is the larger of the suffix maximum at i and the prefix maximum at i + k - 1. It is also O(n) time, with O(n) extra space for the two arrays, and it is a good answer when the interviewer asks for a second method.
9Conclusion
We found the maximum of every window of k numbers with a monotonic deque of indexes. A new number pops every smaller or equal number from the back, because those can never be the tallest hill in view again; the front leaves once its index falls out of the window; and the front is always the current maximum. Each index enters and leaves once, so the work is O(n) time and O(k) space, against O(n x k) for rescanning. The clue to remember is a fixed-size window whose summary cannot be updated by subtraction, such as a maximum: keep a deque of the candidates that could still win.
Open with
I will assume k is between one and n, values can be negative or repeated, and I return the maximum of each of the n minus k plus one windows.
Then, if they want more
Rescanning each window is n times k, and a running maximum fails because when the maximum leaves I cannot subtract it. A heap with lazy deletion gets n log n.
The key observation is that when a new number arrives, every older number in the window that is smaller or equal can never be a maximum again, because the new one is at least as large and stays longer. So I keep a deque of indexes whose values fall from front to back.
For each i, I first remove the front if it is i minus k or older, since it has left the window. Then I pop from the back while the back value is at most a of i, and push i. Once i is at least k minus one, the front holds the window's maximum and I record it.
Each index is pushed once and popped at most once, so it is O(n) time and O(k) space, and storing indexes lets me tell when the front expires.
About this answer
- Last updated
- 14 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 19 times in that collection. How it is counted
- Official documentation
- ArrayDeque (Java 21), Arrays (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "For every window of k consecutive elements in an array, report the maximum.": https://scrivio-interview-library.netlify.app/data-structures/solutions/for-every-window-of-k-consecutive-elements-in-an-array-report-th-2a3d9f/