Sliding Window Maximum — LeetCode 239 Python Solution

HardQueueArraySliding WindowMonotonic QueueHeap (Priority Queue)
Problem
#239
Reading time
2 min

The problem

You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window.

Example

Input
nums = [1,3,-1,-3,5,3,6,7], k = 3
Output
[3,3,5,5,6,7]
Explanation
Window position Max

Python solution

Python
class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        q = [(-v, i) for i, v in enumerate(nums[: k - 1])]
        heapify(q)
        ans = []
        for i in range(k - 1, len(nums)):
            heappush(q, (-nums[i], i))
            while q[0][1] <= i - k:
                heappop(q)
            ans.append(-q[0][0])
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log k)
SpaceO(k) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 239. Sliding Window Maximum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Sliding Window.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

On a study list

This problem is on NeetCode 150.

Frequently asked questions

How hard is LeetCode 239. Sliding Window Maximum?
LeetCode 239. Sliding Window Maximum is rated Hard on LeetCode.
What is the time complexity of LeetCode 239. Sliding Window Maximum?
The Python solution on this page runs in O(n \times \log k).
What is the space complexity of LeetCode 239. Sliding Window Maximum?
The Python solution on this page uses O(k) auxiliary space.
What topics does LeetCode 239. Sliding Window Maximum cover?
LeetCode 239. Sliding Window Maximum is tagged Queue, Array, Sliding Window, Monotonic Queue and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview