Problem 259787 · medium · Phase 02 Linear Data Structures

Largest in Every Window

arrays · sliding window · deque

Given a list of integers nums and a positive integer k, return a list with the maximum of every contiguous window of exactly k elements, from left to right. If k is larger than the list, return [].

Examples

Input:  nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
Output: [3, 3, 5, 5, 6, 7]

Input:  nums = [4, 4, 4, 4], k = 2
Output: [4, 4, 4]

Constraints

  • 0 <= len(nums) <= 10**5
  • 1 <= k <= 10**5
  • Return a new list.
  • Target: O(n) time; taking max of each window separately is too slow for large k.

Goals

  • Maintain candidates for the window maximum in a deque
  • Drop indices that leave the window
  • Achieve linear time for any window size
Starting Python…