Taro Logo

Sliding Window Maximum

Hard
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+32
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
2.2K views
Topics:
ArraysSliding WindowsStacks

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 <= 105
  • -104 <= nums[i] <= 104
  • 1 <= k <= nums.length

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the input array `nums` is empty or if `k` is greater than the length of the array?
  2. Can the input array contain negative numbers, zeros, or duplicate values?
  3. Should the output be an array containing the maximum values themselves, or should it return their indices?
  4. Are there any memory constraints on the output array, or can I allocate a new array of size `n - k + 1` for the results?
  5. Is `k` guaranteed to be at least 1 and less than or equal to the length of the array?

Brute Force Solution

Approach

Imagine looking at a long row of numbers through a small viewing frame that reveals only a few numbers at a time. The brute force strategy involves manually sliding that frame step by step and, at every single stop, looking at all the numbers inside the frame to find the largest one.

Here's how the algorithm would work step-by-step:

  1. Place the viewing frame over the very first group of numbers at the beginning of the row.
  2. Look at every single number currently visible inside the frame.
  3. Compare all of those visible numbers against each other to figure out which one is the biggest.
  4. Write down that biggest number as your answer for this specific position of the frame.
  5. Slide the frame one spot to the right so it covers a slightly different group of numbers.
  6. Repeat the process of looking at all the numbers inside the frame, comparing them, and writing down the biggest one.
  7. Continue sliding the frame one spot at a time and finding the biggest number inside until the frame reaches the very end of the row.

Code Implementation

def max_sliding_window(nums, window_size):
    if not nums or window_size <= 0:
        return []

    maximum_results = []

    # Iterate through all possible starting positions of the sliding window
    for start_index in range(len(nums) - window_size + 1):
        current_maximum = nums[start_index]

        # Inspect every element within the current window to find the largest value
        for offset in range(1, window_size):
            element_index = start_index + offset

            if nums[element_index] > current_maximum:
                current_maximum = nums[element_index]

        # Store the maximum value found for this specific window position
        maximum_results.append(current_maximum)

    return maximum_results

Big(O) Analysis

Time Complexity
O(n * k) – For each of the n minus k plus 1 positions where the viewing frame stops, we must iterate through k elements to find the maximum value. This means that as the frame slides across the array, we repeatedly scan k elements for every single stop. Summing these checks together results in approximately n * k operations. Simplifying this expression yields a final time complexity of O(n * k), or O(n squared) in the worst-case scenario where k approaches n.
Space Complexity
O(k) – The space complexity is determined by the size of the sliding window, denoted as k, which represents the maximum number of elements stored in our data structure at any given time. As the frame slides across the array of size N, the auxiliary memory required to keep track of the elements inside the window remains bounded by k. Since k is independent of N and typically much smaller, the extra memory used scales directly with the window size rather than the total input length. Therefore, simplifying this auxiliary storage usage gives a final space complexity of O(k).

Optimal Solution

Approach

Instead of repeatedly searching for the biggest item in every group, we can maintain a neat line of potential winners as we scan through the sequence. This clever shortcut lets us instantly know the champion of each group without wasting time rechecking items we have already looked at.

Here's how the algorithm would work step-by-step:

  1. Begin scanning through the items from the very beginning, moving forward one step at a time.
  2. As you look at each new item, clear out any older, smaller items from your mental list because they can never be the champion if a bigger or newer item is present.
  3. Add the current item to your mental list of potential champions, keeping everything ordered from biggest to smallest.
  4. Check if the oldest item on your mental list has fallen out of the current viewing window, and if so, gently push it off the list.
  5. Once your viewing window has fully formed, look at the front of your mental list to instantly find the champion for that specific window.
  6. Slide your viewing window forward by one position and repeat the process until you run out of items.

Code Implementation

from collections import deque


def max_sliding_window(array_of_numbers, window_size):
    potential_champion_indices = deque()
    maximum_values_result = []

    for current_index, current_value in enumerate(array_of_numbers):
        # Older smaller items can never win if a larger current item arrives.
        while potential_champion_indices and array_of_numbers[potential_champion_indices[-1]] <= current_value:
            potential_champion_indices.pop()

        potential_champion_indices.append(current_index)

        # Remove indices that have fallen out of the current viewing window boundary.
        if potential_champion_indices[0] <= current_index - window_size:
            potential_champion_indices.popleft()

        # Only record the champion once the viewing window has fully formed.
        if current_index >= window_size - 1:
            maximum_values_result.append(array_of_numbers[potential_champion_indices[0]])

    return maximum_values_result

Big(O) Analysis

Time Complexity
O(n) – As we scan through all n elements of the array from beginning to end, each element is pushed into and popped from our deque at most once. Because adding and removing elements from both ends of the deque takes constant time per operation, the total work scales linearly with the input size. This constant number of operations per element leads to approximately 2n total deque operations, which simplifies to the final Big O time complexity of O(n).
Space Complexity
O(k) – The space complexity is driven by the mental list of potential champions, which is implemented as a double-ended queue. As we scan through the N elements, this data structure stores at most k indices of the array at any given time, where k is the size of the sliding window. Older or smaller elements that can no longer be champions are continuously removed from this deque. Therefore, the extra memory used scales directly with the window size k rather than the total input size N, simplifying to Big O of k.

Edge Cases

Window size k is larger than the array length nums.length
How to Handle:
The algorithm should handle this by clamping the window size or returning an empty array since a valid window cannot be formed.
Window size k equals 1
How to Handle:
Every element in the array is its own maximum, so the output array should be an exact copy of the input array.
Window size k equals the array length nums.length
How to Handle:
The sliding window covers the entire array once, resulting in an output array containing a single element which is the maximum of the whole array.
Array contains all identical values
How to Handle:
The monotonic queue will maintain duplicate indices, but correctly output that same constant value for every window position.
Array is strictly decreasing
How to Handle:
The monotonic queue stores elements efficiently by removing smaller elements, always keeping the first element of the window as the maximum.
Array is strictly increasing
How to Handle:
The monotonic queue continually pops older smaller elements from the back, ensuring the newest and largest element is always at the front for each window.
Array contains negative numbers and zeros
How to Handle:
Using a monotonic queue of indices rather than values ensures we correctly compare signed integers and track positions regardless of magnitude.
Extremely large input arrays near memory or time limits
How to Handle:
An optimized O(n) deque approach processes each element at most twice, preventing Time Limit Exceeded errors on massive datasets.
0/75 completed