Stacks and Monotonic Structures
37 / 170Stacks and Monotonic StructuresLesson 7 of 8About 73 min
The window from Unit 3 meets the discard rule from this one. This is why the problem waited.
This is the sliding-window problem that Unit 3 skipped. A window slides across an array and you must report an extreme value for every position it occupies.
Recomputing from scratch is O(n times k). A window cannot roll an extreme the way it rolls a sum, because when the current extreme leaves the window there is nothing stored to fall back on. The missing piece is the monotonic discard rule from this unit.
The lab below asks only for the maintenance rules, with no windowing around them. Get those right in isolation, then the problem is mostly assembling them into a loop.
Build the two rules on their own. push_candidate adds an index to the back of a deque of indexes, first discarding from the back every index whose value is smaller than the incoming one, and returns the deque. expire_front removes front indexes that have fallen outside a window starting at window_start, and returns the deque. front_value reports the value at the front, or None when empty.
Tests
values = [1, 3, -1, -3, 5]candidates = deque()for index in range(4): push_candidate(candidates, values, index)print(list(candidates))print(front_value(candidates, values))expire_front(candidates, 2)print(list(candidates), front_value(candidates, values))push_candidate(candidates, values, 4)print(list(candidates), front_value(candidates, values))print(front_value(deque(), values))Output
Run tests to see output.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.