Streaming Minimums Over Bounded Windows
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given an integer array nums of length n and a positive window capacity k, process the elements of nums one by one from left to right.
Upon reading nums[i] (0 <= i < n), compute the smallest value inside the trailing subarray nums[start .. i], where start = max(0, i - k + 1). That trailing subarray holds at most k elements: for the initial positions i < k - 1, fewer than k values have arrived so far and the subarray spans nums[0 .. i]; once i >= k - 1, the subarray holds the most recent k elements ending at i.
Return an integer list of length n whose i-th entry is that trailing-window minimum. Your algorithm should determine each output online as nums[i] arrives and finish in O(n) total time.
def sliding_window_minimums(nums: List[int], k: int) -> List[int]:
pass
Examples
Example 1
Input: nums = [8, 3, 6, 2, 7, 5, 9], k = 3
Output: [8, 3, 3, 2, 2, 2, 5]
Walk-through:
- i = 0: [8] -> 8
- i = 1: [8, 3] -> 3
- i = 2: [8, 3, 6] -> 3
- i = 3: [3, 6, 2] -> 2
- i = 4: [6, 2, 7] -> 2
- i = 5: [2, 7, 5] -> 2
- i = 6: [7, 5, 9] -> 5 (2 at index 3 has slid past start = 4, so 5 becomes the new minimum)
Example 2
Input: nums = [9, -4, 12, 0], k = 1
Output: [9, -4, 12, 0]
Walk-through: When k = 1, each trailing window contains only [nums[i]], so every step returns nums[i] directly.
Example 3
Input: nums = [5, -2, 4, -2, -6], k = 8
Output: [5, -2, -2, -2, -6]
Walk-through: Because k = 8 is larger than len(nums) = 5, start stays 0 at every index and the output records the running prefix minimums of nums, still producing 5 entries.
Constraints
1 <= len(nums) <= 2 * 10^51 <= k <= 10^5-2^31 <= nums[i] <= 2^31 - 1- Target complexity:
O(n)time in a single streaming pass.
Step-by-step walkthrough
Understand the streaming window rule
As numbers arrive one by one from left to right, at every index
iwe must output the smallest number insidenums[start .. i], wherestart = max(0, i - k + 1).Notice how this differs from the textbook "full windows only" variant:
- For the first
k - 1steps (i = 0, 1, ..., k - 2), fewer thankelements have arrived so far, sostart = 0and the window is simplynums[0 .. i]. - Once
i >= k - 1, the window has full lengthkand slides one step right with each new element. - Therefore, an input of length
nalways producesnoutputs — even whenk > n!
nums = [8, 3, 6, 2, 7, 5, 9], k = 3 i = 0: [8] -> min = 8 (partial window, length 1) i = 1: [8, 3] -> min = 3 (partial window, length 2) i = 2: [8, 3, 6] -> min = 3 (full window, length 3) i = 3: [3, 6, 2] -> min = 2 i = 4: [6, 2, 7] -> min = 2 i = 5: [2, 7, 5] -> min = 2 i = 6: [7, 5, 9] -> min = 5 (index 3's 2 slid out!)- For the first
Why scanning every window from scratch is too slow
Calling
min(nums[window_start : i + 1])at every indexicompares up tokelements per step, costingO(n * k)time overall. Withn = 200,000andk = 100,000,n * kreaches roughly10^10comparisons — seconds or minutes instead of milliseconds.The waste comes from throwing away work: when the window slides from
[3, 6, 2]to[6, 2, 7],6and2were already compared in the previous step!Key insight: an older, larger element can never win again
Ask yourself: when a new number
valuearrives at indexi, which earlier numbers inside the current window could possibly be the minimum now or at any point in the future?Suppose an earlier index
j < ihasnums[j] >= nums[i]:Index: ... j i ... Value: 6 2 ^ ^ older & larger newer & smaller!Every future window that still includes
jwill also includei(becauseiis to the right ofjand leaves the window later), andnums[i]is already smaller than or equal tonums[j]. That meansnums[j]is permanently useless — we can throw it away immediately!If we discard every older entry
>= valuewhenever a newvaluearrives, the surviving candidates from oldest to newest must have strictly increasing values (for example,(index=3, val=2)followed by(index=5, val=5)).To update both ends in
O(1)time, we store these surviving(index, value)pairs in a deque (collections.deque, a double-ended queue supporting fastappend/popat the right end andpopleftat the left end). Because its values stay sorted in one direction, this structure is called a monotonic deque.Three small steps per incoming element
For each incoming
(i, value):- Expire the front (
popleft): Computewindow_start = max(0, i - k + 1). While the oldest candidatewindow[0]hasindex < window_start, it has slid out of the window, so pop it from the left. - Prune dominated candidates at the back (
pop), then append: While the newest candidatewindow[-1]hasvalue >= current value, pop it from the right. Then append(i, value). - Read the minimum at
window[0]: Because surviving values strictly increase from front to back,window[0][1]is guaranteed to be the minimum of the active window!
Why store
(i, value)pairs instead of bare indicesi? In a true stream, old elements ofnumsdo not need to be kept in memory — keeping(i, value)inside the deque uses at mostO(k)memory total without ever indexing back intonums.window: deque = deque() ans: List[int] = [] for i, value in enumerate(nums): window_start = max(0, i - k + 1) # Phase 1: Evict candidates at the front that slid left past window_start. while window and window[0][0] < window_start: window.popleft() # Phase 2: Evict older candidates at the back with value >= current value. while window and window[-1][1] >= value: window.pop() window.append((i, value)) # Phase 3: Since values strictly increase from front to back, window[0] is the minimum. ans.append(window[0][1])- Expire the front (
Trace Example 1 (showing both back-popping and front-expiration)
Let's trace Example 1 (
nums = [8, 3, 6, 2, 7, 5, 9],k = 3), writing each deque item asindex:value:i val window_start evict front pop back deque (front -> back) ans[i] - --- ------------ ----------------- ------------- --------------------- ------ 0 8 0 - - [0:8] 8 1 3 0 - 0:8 (8 >= 3) [1:3] 3 2 6 0 - - [1:3, 2:6] 3 3 2 1 - 2:6, 1:3 [3:2] 2 4 7 2 - - [3:2, 4:7] 2 5 5 3 - 4:7 (7 >= 5) [3:2, 5:5] 2 6 9 4 3:2 (idx 3 < 4!) - [5:5, 6:9] 5Notice step
i = 6: when3:2expires off the front (3 < 4), the runner-up candidate5:5is already waiting right behind it at the new front of the deque!Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def sliding_window_minimums(nums: List[int], k: int) -> List[int]: """Return ans[i] = min(nums[max(0, i - k + 1) .. i]) in one streaming O(n) pass.""" # window: deque of (index, value) pairs, e.g. deque([(3, 2), (5, 5)]), kept so both # indices and values strictly increase from front (window[0]) to back (window[-1]). window: deque = deque() ans: List[int] = [] for i, value in enumerate(nums): # Active window covers indices [window_start .. i] (shorter than k when i < k - 1). window_start = max(0, i - k + 1) # Phase 1: Evict candidates at the front that slid left past window_start. while window and window[0][0] < window_start: window.popleft() # Phase 2: Evict older candidates at the back with value >= current value. # Because `value` is <= them AND sits at a newer index `i`, those older entries # can never be the minimum of this window or any future window. while window and window[-1][1] >= value: window.pop() window.append((i, value)) # Phase 3: Since values strictly increase from front to back, window[0] is the minimum. ans.append(window[0][1]) return ans✅ Submit now — all tests should pass.
Intuition & how it works
Imagine tracking the cheapest hotel nightly rate offered over the last k days: each morning a new day's rate arrives, and any quote older than k days expires. Notice a huge shortcut: if Tuesday's rate is 120 and Wednesday's rate is 90, Tuesday's quote is both more expensive than Wednesday's AND expires earlier than Wednesday's — so Tuesday can never be the cheapest rate of any window from Wednesday onward, and you can cross Tuesday off your notepad immediately!
Why does the naive approach fall short? Slicing the last k numbers and scanning all of them on every step repeats up to k comparisons for each of the n arrivals, costing O(n * k) time (up to 2 * 10^10 operations when n = 200,000 and k = 100,000). Instead, we store only non-dominated (index, value) candidates in a deque (a double-ended queue that adds or removes items from either the front or the back in O(1) time). Because we pop every older value >= the newcomer from the back, the remaining values stay sorted from smallest to largest — a pattern called a monotonic deque.
Walk through nums = [8, 3, 6, 7] with k = 2:
i=0 (val=8, window [0..0]): deque = [(0, 8)] -> front is 8
i=1 (val=3, window [0..1]): 8 >= 3 so pop (0, 8);
deque = [(1, 3)] -> front is 3
i=2 (val=6, window [1..2]): index 1 >= 1 (keep); 3 < 6;
deque = [(1, 3), (2, 6)] -> front is 3
i=3 (val=7, window [2..3]): index 1 < 2 so expire (1, 3) from front;
deque = [(2, 6), (3, 7)] -> front is 6
Result: [8, 3, 3, 6]
Complexity
Let n be len(nums) and k be the window size.
- Time:
O(n)total (O(1)amortized per element). Although the innerwhileloops can pop several elements on a single step, every(i, value)pair is appended towindowonce and popped at most once (either expired from the front or dominated from the back). Across allnsteps, total pushes and pops never exceed2n(amortizedO(1)time means occasional multi-pop steps are paid for by earlier push-only steps, averaging constant work per item). - Space:
O(min(n, k))auxiliary space (plusO(n)for the returnedanslist). After Phase 1 evicts indices< max(0, i - k + 1), every surviving pair inwindowbelongs to the current window of at mostmin(n, k)indices. Even better, on a constant stream like[5, 5, 5, ...], popping>=keeps only1item in the deque!
Edge cases
- Partial initial windows (
i < k - 1):window_start = max(0, i - k + 1)evaluates to0, so the firstk - 1outputs are simply running prefix minimums andlen(ans)is stilln. k == 1(Example 2): Every previous element (index == i - 1 < i) is evicted immediately in Phase 1, returning a copy ofnums.k >= n(Example 3 withn = 5, k = 8):window_startstays0for the entire pass, so nothing ever expires from the front andansequals the running prefix minimums.- Duplicate minimum values (
[2, 2, 5],k = 2): Ati = 1,(0, 2)is popped because2 >= 2and replaced by(1, 2), which stays valid throughi = 2and rightly reports2. - Strictly increasing vs. strictly decreasing inputs: Increasing inputs grow the deque up to size
kand test front expiration on every step; decreasing inputs keep the deque at size1and test back eviction on every step. - 32-bit signed extremes (
-2^31to2^31 - 1): We only compare input integers directly without adding or subtracting values, so overflow cannot occur even in fixed-width languages.
Common mistakes
- Returning
n - k + 1outputs instead ofn: Classic sliding-window problems skip the firstk - 1indices, whereas this streaming specification requires an output at every index starting ati = 0. - Using a Python
listwithwindow.pop(0)instead ofcollections.deque:list.pop(0)shifts every remaining element left inO(k)time, silently degrading increasing inputs back toO(n * k)! - Off-by-one errors in the expiration check: The window
[i - k + 1 .. i]containskelements, so an index is expired whenidx < i - k + 1(equivalentlyidx <= i - k). Writingidx < i - kleaves a(k + 1)-th stale minimum alive for one extra step! - Storing only values without indices: If you omit indices and try to expire by checking
if window[0] == nums[i - k]: window.popleft(), popping>=on duplicates breaks: on[2, 2, 3]withk = 2,(0, 2)was already replaced by(1, 2), so ati = 2comparingnums[0] == 2mistakenly evicts index1's2!
Alternative approaches
- Min-heap with lazy deletion (
O(n log n)time,O(n)space): A min-heap is a binary tree stored in an array whose smallest element sits at index0inO(1)time withO(log n)insertions and removals. Push(value, i)at each step, and use lazy deletion (leaving expired items inside the heap until they bubble to the topheap[0][1] < window_start, then popping them). Easy to code, but slower (O(n log n)) and can holdO(n)stale items on strictly decreasing streams. - Two-stack queue with prefix minimums (
O(n)time,O(k)space): Simulate a queue of sizekusing anin_stackandout_stackwhere each node also tracks the minimum below it. Useful when the operation has no ordering shortcut (for example, sliding-window greatest common divisor or matrix product), though slightly bulkier than a monotonic deque formin/max.
Follow-up questions
- How would you refactor this into a stateful class for an infinite data stream so memory stays strictly O(k)? Wrap the state inside a
StreamingWindowMin(k)class storing onlyself.k,self.window = deque(), andself.next_index = 0. Eachpush(value) -> intcall incrementsself.next_index, runs the exact same front-eviction and back-popping loops withwindow_start = max(0, i - self.k + 1), and returnsself.window[0][1]. Because(index, value)pairs live directly insideself.window, older stream items are never retained and memory never exceedsO(k)regardless of how long the stream runs.
class StreamingWindowMin:
def __init__(self, k: int) -> None:
self.k = k
self.window: deque = deque()
self.next_index = 0
def push(self, value: int) -> int:
i = self.next_index
self.next_index += 1
window_start = max(0, i - self.k + 1)
while self.window and self.window[0][0] < window_start:
self.window.popleft()
while self.window and self.window[-1][1] >= value:
self.window.pop()
self.window.append((i, value))
return self.window[0][1]
- Suppose each reading carries a millisecond timestamp and the window covers the trailing T milliseconds rather than the last k items—what changes? Store
(timestamp_ms, value)in the deque instead of(index, value), and change Phase 1 towhile window and window[0][0] < now_ms - T: window.popleft()(or<=depending on whether[now - T, now]is open or closed on the left). Unlike count-based windows where at most one candidate expires per arrival, a quiet gap between readings can expire many entries at once — which thewhileloop handles naturally inO(1)amortized time per reading! Peak space becomesO(M), whereMis the largest burst of arrivals within anyT-millisecond span. - How could you report both the trailing-window minimum and the trailing-window maximum after every arrival while keeping O(n) total runtime? Maintain two separate monotonic deques side by side inside the same loop:
min_window(popping>= valuefrom the back so values strictly increase) andmax_window(popping<= valuefrom the back so values strictly decrease). Each arrival enters and leaves each deque at most once, keeping overall runtimeO(n)and extra spaceO(k).
Follow-up questions
- How would you refactor this into a stateful class for an infinite data stream so memory stays strictly O(k)?
- Suppose each reading carries a millisecond timestamp and the window covers the trailing T milliseconds rather than the last k items—what changes?
- How could you report both the trailing-window minimum and the trailing-window maximum after every arrival while keeping O(n) total runtime?
Similar questions
- Evaluate Four-Operator Arithmetic Strings
- Reference-Counted SharedPtr Template in C++
- Integrating Vision-Language Models Safely into Autonomous Driving
- Securing Executive Buy-In for Foundation Models in Autonomous Driving
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger