Skip to content
CodeItRaw
Stacks & Queues

Lesson 4/4

Putting the index on the stack instead of the value gives you two things at once: the value (values[i]) and the place. In questions like "how many days to wait?" the answer is the difference of two places; had you stored the value you could not work it out.

from collections import deque
window = deque()
for i, v in enumerate(values):
while window and values[window[-1]] <= v:
window.pop()
window.append(i)
if window[0] <= i - size:
window.popleft()
For the largest of a sliding window you need to drop elements from both ends: from the back, those smaller than the newcomer (they can never be a window's largest again); from the front, the one that has left the window. A deque does either end in one step; the window's largest is always at window[0].

A stack uses one end (last in, first out), a queue both (first in, first out). pop(0) at the front of a list shifts every remaining element; when you need a queue, use a deque.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    A Warmer Day

    Function

  2. 02

    Window Peaks

    Function

If you would rather not wait for the order, every problem is open without locks: Problem list