KatInterview

239. Sliding Window Maximum

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the maximum value in a sliding window of size k as it moves across an array nums. A naive approach would be to iterate through each of the n - k + 1 windows and, for each window, find its maximum element. This takes O(k) time per window, leading to a total time complexity of O(n*k). Given the constraint n <= 10^5, this approach is too slow and would result in a "Time Limit Exceeded" error. We need a more efficient method that avoids re-computing the maximum from scratch for each window.

Solution

Sliding Window Maximum in Python

from collections import deque

class Solution:
    def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:
        if not nums or k == 0:
            return []
        
        n = len(nums)
        result = []
        # Deque stores indices of elements in the current window.
        # It is maintained such that elements corresponding to these indices are in decreasing order.
        dq = deque()

        for i in range(n):
            # 1. Remove indices from the front that are out of the current window.
            # The window is [i - k + 1, i]. An index `j` is out if `j < i - k + 1`.
            if dq and dq[0] < i - k + 1:
                dq.popleft()

            # 2. Maintain the monotonic decreasing property of the deque.
            # Remove indices from the back whose corresponding elements are smaller than the current element.
            while dq and nums[dq[-1]] < nums[i]:
                dq.pop()

            # 3. Add the current index to the back.
            dq.append(i)

            # 4. If the window has reached size k, the front of the deque is the max.
            # This condition `i >= k - 1` is true for the first full window and all subsequent windows.
            if i >= k - 1:
                # The front of the deque always holds the index of the maximum element in the current window.
                result.append(nums[dq[0]])

        return result

Sliding Window Maximum in Java

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums == null || nums.length == 0 || k == 0) {
            return new int[0];
        }
        int n = nums.length;
        int[] result = new int[n - k + 1];
        int resultIndex = 0;
        
        // Deque stores indices of elements in the current window.
        // It is maintained such that elements corresponding to these indices are in decreasing order.
        Deque<Integer> dq = new ArrayDeque<>();

        for (int i = 0; i < n; i++) {
            // 1. Remove indices from the front that are out of the current window.
            // The window is [i - k + 1, i]. An index `j` is out if `j < i - k + 1`.
            if (!dq.isEmpty() && dq.peekFirst() < i - k + 1) {
                dq.pollFirst();
            }

            // 2. Maintain the monotonic decreasing property of the deque.
            // Remove indices from the back whose corresponding elements are smaller than the current element.
            while (!dq.isEmpty() && nums[dq.peekLast()] < nums[i]) {
                dq.pollLast();
            }

            // 3. Add the current index to the back.
            dq.offerLast(i);

            // 4. If the window has reached size k, the front of the deque is the max.
            // This condition `i >= k - 1` is true for the first full window and all subsequent windows.
            if (i >= k - 1) {
                // The front of the deque always holds the index of the maximum element in the current window.
                result[resultIndex++] = nums[dq.peekFirst()];
            }
        }
        return result;
    }
}

Sliding Window Maximum in C++

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        vector<int> result;
        // Deque will store indices of elements in the current window.
        // It's maintained in a way that the elements corresponding to these indices are in decreasing order.
        deque<int> dq; 

        for (int i = 0; i < nums.size(); ++i) {
            // 1. Remove indices from the front that are out of the current window.
            // The window is [i - k + 1, i]. An index `j` is out if `j < i - k + 1`.
            if (!dq.empty() && dq.front() < i - k + 1) {
                dq.pop_front();
            }

            // 2. Maintain the monotonic decreasing property of the deque.
            // Remove indices from the back whose corresponding elements are smaller than the current element.
            while (!dq.empty() && nums[dq.back()] < nums[i]) {
                dq.pop_back();
            }

            // 3. Add the current index to the back.
            dq.push_back(i);

            // 4. If the window has reached size k, the front of the deque is the max.
            // This condition `i >= k - 1` is true for the first full window and all subsequent windows.
            if (i >= k - 1) {
                // The front of the deque always holds the index of the maximum element in the current window.
                result.push_back(nums[dq.front()]);
            }
        }
        return result;
    }
};

Sliding Window Maximum in TypeScript

function maxSlidingWindow(nums: number[], k: number): number[] {
    if (!nums || nums.length === 0 || k === 0) {
        return [];
    }
    const n = nums.length;
    const result: number[] = [];
    // Deque stores indices of elements in the current window.
    // It is maintained such that elements corresponding to these indices are in decreasing order.
    const dq: number[] = []; // Using a regular array as a deque

    for (let i = 0; i < n; i++) {
        // 1. Remove indices from the front that are out of the current window.
        // The window is [i - k + 1, i]. An index `j` is out if `j < i - k + 1`.
        if (dq.length > 0 && dq[0] < i - k + 1) {
            dq.shift(); // Remove from front
        }

        // 2. Maintain the monotonic decreasing property of the deque.
        // Remove indices from the back whose corresponding elements are smaller than the current element.
        while (dq.length > 0 && nums[dq[dq.length - 1]] < nums[i]) {
            dq.pop(); // Remove from back
        }

        // 3. Add the current index to the back.
        dq.push(i);

        // 4. If the window has reached size k, the front of the deque is the max.
        // This condition `i >= k - 1` is true for the first full window and all subsequent windows.
        if (i >= k - 1) {
            // The front of the deque always holds the index of the maximum element in the current window.
            result.push(nums[dq[0]]);
        }
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.