Skip to content

Interview Solver

FeaturesPricingHelp
Sign In
FeaturesPricingHelpSign In
  1. Interview Questions
  2. /
  3. Problems
  4. /
  5. Sliding Window Maximum

Sliding Window Maximum

Report the largest value in every window of k consecutive elements. The go-to problem for the monotonic deque, which gets each answer in amortized O(1). Solve it below in Python or JavaScript, then read the walkthrough.

HardArrayQueueSliding WindowHeap (Priority Queue)Monotonic QueueRange Minimum/Maximum QueryAsked at 131 companies incl. Google, Amazon, Meta

Problem

You're given an integer array nums and a window size k. Slide a window of exactly k consecutive elements from the left end of the array to the right end, one position at a time.

Return an array containing the maximum of each window, in order from left to right. There are nums.length - k + 1 windows in total.

Example 1

Input
nums = [4, 2, 12, 3, 8, 1, 5], k = 3
Output
[12, 12, 12, 8, 8]

The windows are [4,2,12], [2,12,3], [12,3,8], [3,8,1] and [8,1,5]. The 12 stays the maximum until the window slides past it.

Example 2

Input
nums = [5], k = 1
Output
[5]

Example 3

Input
nums = [9, 7, 5, 3, 1], k = 2
Output
[9, 7, 5, 3]

In a decreasing array, each window’s maximum is its leftmost element.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • 1 ≤ k ≤ nums.length

Practice

1
2
3
4

Runs 11 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.

Get asked Sliding Window Maximum in a real interview?

Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.

Start Free Trial

How to solve Sliding Window Maximum

Pattern: Monotonic deque

The key observation: once a bigger number arrives, every smaller number to its left is useless for the rest of the scan. Any future window that contains the smaller, older number also contains the bigger, newer one, so the older one can never be the maximum again.

So keep only the candidates that could still win: a deque of indices whose values are strictly decreasing from front to back. When a new value comes in, pop smaller (or equal) values off the back, since they've just become useless. Then push the new index. The front of the deque is always the current maximum, and you pop it off the front once it slides out of the window.

Spot this pattern when you need a running max or min over a window that moves in one direction. A heap also works, but the deque throws away dominated values instead of keeping them around.

Approach 1: Brute force: scan each window

For each of the n - k + 1 windows, loop over its k elements and take the maximum. Fine for small inputs, but with n = 10⁵ and k = 5 × 10⁴ it does billions of comparisons.

Time O(n · k) · Space O(1) extra

Approach 2: Max-heap with lazy deletion

Push (value, index) pairs into a max-heap as the window grows. Before reading the top, pop entries whose index has fallen out of the window. Stale entries are only removed when they reach the top, so the heap can hold up to n items.

Time O(n log n) · Space O(n)

Approach 3: Monotonic deque of indices

For each index i:

  1. If the front index is ≤ i - k, it has left the window: pop it from the front.
  2. While the value at the back is ≤ nums[i], pop it from the back.
  3. Push i on the back.
  4. Once i ≥ k - 1, the window is full, so record nums[front].

Every index is pushed once and popped at most once, so the total work is linear even though a single step can pop many items.

Time O(n) · Space O(k)

ApproachTimeSpace
Brute force: scan each windowO(n · k)O(1) extra
Max-heap with lazy deletionO(n log n)O(n)
Monotonic deque of indicesO(n)O(k)

Solution code

Try the practice editor first. Both solutions pass every test above.

▸Sliding Window Maximum solution in Python
from collections import deque


def max_sliding_window(nums: list[int], k: int) -> list[int]:
    window = deque()  # indices, values strictly decreasing
    result = []
    for i, num in enumerate(nums):
        if window and window[0] <= i - k:
            window.popleft()
        while window and nums[window[-1]] <= num:
            window.pop()
        window.append(i)
        if i >= k - 1:
            result.append(nums[window[0]])
    return result
▸Sliding Window Maximum solution in JavaScript
function maxSlidingWindow(nums, k) {
  const dq = new Array(nums.length); // indices, values strictly decreasing
  let head = 0;
  let tail = 0;
  const result = [];
  for (let i = 0; i < nums.length; i++) {
    if (head < tail && dq[head] <= i - k) head++;
    while (head < tail && nums[dq[tail - 1]] <= nums[i]) tail--;
    dq[tail++] = i;
    if (i >= k - 1) result.push(nums[dq[head]]);
  }
  return result;
}

Common mistakes

  • Storing values instead of indices in the deque, which leaves no way to tell when the front has slid out of the window.
  • Recording a result before the first window is full (before i reaches k - 1).
  • Using a plain array with shift() in JavaScript or list.pop(0) in Python, which is O(n) per call. Use collections.deque, or a head pointer into an array.
  • Calling the approach O(n · k) because of the inner while loop. Each index is popped at most once over the whole run, so it is O(n) total.

What interviewers look for

Start with the brute force and its O(n · k) cost, then ask what work is repeated: neighboring windows share k - 1 elements. The heap is a reasonable middle step and worth mentioning.

The part interviewers listen for is the dominance argument: "if a newer element is at least as big, the older one can never be a window maximum again, so I can throw it away." Once you've said that, the decreasing deque follows, and the amortized O(n) argument (each index enters and leaves once) is the second thing they'll ask about.

Follow-up questions

How would you get the minimum of each window instead?

Flip the comparison: keep a deque with increasing values, popping from the back while the back is greater than or equal to the new value.

What if the data arrives as a stream and you must emit each window’s maximum as soon as it is complete?

The deque algorithm already works online. It only looks at the newest element and the deque, so you can emit the front after each arrival once k elements have been seen, using O(k) memory.

What about the median of each window?

The deque trick does not apply because the median is not determined by dominance. Use two heaps (a max-heap for the lower half and a min-heap for the upper half) with lazy deletion, or a balanced order-statistic tree, for O(n log k).

Companies that ask Sliding Window Maximum

Sliding Window Maximum is tagged by 131 companies in our interview dataset. The score shows how often it comes up at each company.

  • Citadel100%
  • Vistaprint100%
  • Zenefits100%
  • Blinkit100%
  • Line100%
  • Aveva98%
  • Tanla97%
  • Argo Ai92%
  • John Deere91%
  • Algolia90%
  • Alten89%
  • Skyscanner89%
  • Alarmcom88%
  • Fujitsu87%
  • Nutanix86.3%
  • Zepto85.7%
  • Prove84%
  • Notion83%
  • Marqeta83%
  • Yokogawa Electric83%
  • N2681%
  • Arrow Electronics81%
  • Cabaletta Bio81%
  • Dataart81%

and 107 more.

Practice next

  • Top K Frequent ElementsMediumCount, then bucket by frequency
  • Kth Largest Element in an ArrayMediumQuickselect
  • Two SumEasyHash map of complements
  • Number of IslandsMediumFlood fill (DFS/BFS on a grid)

Get live help in the real interview

Working solutions in real time during your actual interview. Invisible to screensharing.

Start Free Trial

No credit card required

Interview Solver
  • Home
  • About
  • Pricing
  • Sign in
  • Contact
  • Blog
  • Companion
  • Mobile
  • Help Center
  • Developers
  • Use Cases
  • Software Engineer
  • Product Manager
  • Misc
  • Privacy Policy
  • Terms and Conditions
  • Refund & Cancellation
  • Discord Community
  • Affiliate Program
  • Compare
  • All Comparisons
  • vs Final Round AI
  • vs UltraCode
  • vs Interview Coder
  • vs LockedIn AI
  • vs AI Apply
  • Free Tools
  • ATS Resume Checker
  • STAR Method Builder
  • Salary Lookup
  • Big O Cheat Sheet
  • Total Comp Calculator
  • View All →
  • Interview Questions
  • Google Questions
  • Amazon Questions
  • Microsoft Questions
  • Meta Questions
  • Apple Questions
  • TikTok Questions
  • View All →
© 2026 Interview Solver, Inc. All rights reserved.