150 XP

98. Maximum of every window

Expert sliding window queues

A window of k items slides along a list one place at a time: first it covers items 0 to k - 1, then 1 to k, and so on, until it reaches the end.

Write a function window_maxes(numbers, k) that returns the largest number in each position of the window, in order. A list of n items has n - k + 1 windows.

  • Numbers can repeat and can be negative.
  • k is at least 1 and at most the length of the list.

Taking max() of every window costs k steps each, n * k in all. There is a way that costs O(n) in all: keep the indexes of the items that could still become a window's maximum, in a deque, their values falling from front to back.

Example 1

Inputnumbers = [4, 2, 12, 3, 8, 1, 5], k = 3
Output[12, 12, 12, 8, 8]
Explanation12 rules the first three windows.

Example 2

Inputnumbers = [9, 8, 7, 6], k = 2
Output[9, 8, 7]
ExplanationEach 9, 8, 7 leaves as the window moves on.

Example 3

Inputnumbers = [5], k = 1
Output[5]
ExplanationOne window of one item.

Constraints

  • numbers has 1 to 500 whole numbers, each from -10^4 to 10^4.
  • k is from 1 to len(numbers).

Submit also runs 8 more tests you can't see.

Practises Modules and Imports (lesson 22).

Code
def window_maxes(numbers, k):
    """Find the maximum of each window of k items.

    numbers: list of int, at least one
    k: int, from 1 to len(numbers)
    Returns: list of int, the maximum of each window, from
        the leftmost window to the rightmost
    """
    # Write your code here
    pass