Taro Logo

Sliding Window Maximum

Hard
Meta logo
Meta
1 view
Topics:
ArraysSliding Windows

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. Each time the sliding window moves right by one position.

Return the max sliding window.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= nums.length

Solution


Brute Force Solution

A naive approach would be to iterate through the array with a sliding window of size k. For each window, find the maximum element. This involves iterating k times for each window.

Code (Python):

def max_sliding_window_brute_force(nums, k):
    if not nums:
        return []
    
    result = []
    for i in range(len(nums) - k + 1):
        window = nums[i:i+k]
        result.append(max(window))
    return result

Big O Analysis:

  • Time Complexity: O(n*k), where n is the length of the input array nums and k is the window size. This is because for each of the n-k+1 windows, we iterate through k elements to find the maximum.
  • Space Complexity: O(n-k+1) in the worst case, where n is the length of the input array nums and k is the size of the sliding window, to store the output array. Can be O(1) if the result is computed in place.

Optimal Solution: Using a Deque

A more efficient solution utilizes a double-ended queue (deque) to maintain a decreasing order of indices of potentially maximum elements within the window.

Algorithm:

  1. Initialize a deque.
  2. Iterate through the array nums.
  3. For each element:
    • Remove elements from the rear of the deque that are smaller than the current element. This ensures the deque maintains a decreasing order.
    • Add the current element's index to the rear of the deque.
    • Remove elements from the front of the deque that are outside the current window (i.e., their index is less than i - k + 1).
    • If the window is full (i.e., i >= k - 1), the front of the deque contains the index of the maximum element in the current window. Add this element to the result.

Code (Python):

from collections import deque

def max_sliding_window(nums, k):
    if not nums:
        return []

    d = deque()
    result = []

    for i in range(len(nums)):
        # Remove elements out of the window
        while d and d[0] <= i - k:
            d.popleft()

        # Remove smaller elements in deque than current element
        while d and nums[d[-1]] <= nums[i]:
            d.pop()

        d.append(i)

        # Add max to results
        if i >= k - 1:
            result.append(nums[d[0]])

    return result

Big O Analysis:

  • Time Complexity: O(n), where n is the length of the input array nums. Each element is added and removed from the deque at most once.
  • Space Complexity: O(k), where k is the window size, for storing the deque.

Edge Cases:

  • Empty input array: Return an empty array.
  • k is 1: Return the original array.
  • k is equal to the length of nums: Return an array with a single element, which is the maximum of nums.
  • k is greater than the length of nums: This violates the constraint. Should throw an IllegalArgumentException.