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^5
  • 1 <= k <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1
  • Target complexity: O(n) time in a single streaming pass.

Step-by-step walkthrough

  1. Understand the streaming window rule

    As numbers arrive one by one from left to right, at every index i we must output the smallest number inside nums[start .. i], where start = max(0, i - k + 1).

    Notice how this differs from the textbook "full windows only" variant:

    • For the first k - 1 steps (i = 0, 1, ..., k - 2), fewer than k elements have arrived so far, so start = 0 and the window is simply nums[0 .. i].
    • Once i >= k - 1, the window has full length k and slides one step right with each new element.
    • Therefore, an input of length n always produces n outputs — even when k > 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!)
    
  2. Why scanning every window from scratch is too slow

    Calling min(nums[window_start : i + 1]) at every index i compares up to k elements per step, costing O(n * k) time overall. With n = 200,000 and k = 100,000, n * k reaches roughly 10^10 comparisons — 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], 6 and 2 were already compared in the previous step!

  3. Key insight: an older, larger element can never win again

    Ask yourself: when a new number value arrives at index i, 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 < i has nums[j] >= nums[i]:

    Index:     ...   j         i   ...
    Value:           6         2
                     ^         ^
              older & larger   newer & smaller!
    

    Every future window that still includes j will also include i (because i is to the right of j and leaves the window later), and nums[i] is already smaller than or equal to nums[j]. That means nums[j] is permanently useless — we can throw it away immediately!

    If we discard every older entry >= value whenever a new value arrives, 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 fast append/pop at the right end and popleft at the left end). Because its values stay sorted in one direction, this structure is called a monotonic deque.

  4. Three small steps per incoming element

    For each incoming (i, value):

    1. Expire the front (popleft): Compute window_start = max(0, i - k + 1). While the oldest candidate window[0] has index < window_start, it has slid out of the window, so pop it from the left.
    2. Prune dominated candidates at the back (pop), then append: While the newest candidate window[-1] has value >= current value, pop it from the right. Then append (i, value).
    3. 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 indices i? In a true stream, old elements of nums do not need to be kept in memory — keeping (i, value) inside the deque uses at most O(k) memory total without ever indexing back into nums.

    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])
    
  5. 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 as index: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]             5
    

    Notice step i = 6: when 3:2 expires off the front (3 < 4), the runner-up candidate 5:5 is already waiting right behind it at the new front of the deque!

  6. 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 inner while loops can pop several elements on a single step, every (i, value) pair is appended to window once and popped at most once (either expired from the front or dominated from the back). Across all n steps, total pushes and pops never exceed 2n (amortized O(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 (plus O(n) for the returned ans list). After Phase 1 evicts indices < max(0, i - k + 1), every surviving pair in window belongs to the current window of at most min(n, k) indices. Even better, on a constant stream like [5, 5, 5, ...], popping >= keeps only 1 item in the deque!

Edge cases

  • Partial initial windows (i < k - 1): window_start = max(0, i - k + 1) evaluates to 0, so the first k - 1 outputs are simply running prefix minimums and len(ans) is still n.
  • k == 1 (Example 2): Every previous element (index == i - 1 < i) is evicted immediately in Phase 1, returning a copy of nums.
  • k >= n (Example 3 with n = 5, k = 8): window_start stays 0 for the entire pass, so nothing ever expires from the front and ans equals the running prefix minimums.
  • Duplicate minimum values ([2, 2, 5], k = 2): At i = 1, (0, 2) is popped because 2 >= 2 and replaced by (1, 2), which stays valid through i = 2 and rightly reports 2.
  • Strictly increasing vs. strictly decreasing inputs: Increasing inputs grow the deque up to size k and test front expiration on every step; decreasing inputs keep the deque at size 1 and test back eviction on every step.
  • 32-bit signed extremes (-2^31 to 2^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 + 1 outputs instead of n: Classic sliding-window problems skip the first k - 1 indices, whereas this streaming specification requires an output at every index starting at i = 0.
  • Using a Python list with window.pop(0) instead of collections.deque: list.pop(0) shifts every remaining element left in O(k) time, silently degrading increasing inputs back to O(n * k)!
  • Off-by-one errors in the expiration check: The window [i - k + 1 .. i] contains k elements, so an index is expired when idx < i - k + 1 (equivalently idx <= i - k). Writing idx < i - k leaves 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] with k = 2, (0, 2) was already replaced by (1, 2), so at i = 2 comparing nums[0] == 2 mistakenly evicts index 1's 2!

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 index 0 in O(1) time with O(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 top heap[0][1] < window_start, then popping them). Easy to code, but slower (O(n log n)) and can hold O(n) stale items on strictly decreasing streams.
  • Two-stack queue with prefix minimums (O(n) time, O(k) space): Simulate a queue of size k using an in_stack and out_stack where 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 for min/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 only self.k, self.window = deque(), and self.next_index = 0. Each push(value) -> int call increments self.next_index, runs the exact same front-eviction and back-popping loops with window_start = max(0, i - self.k + 1), and returns self.window[0][1]. Because (index, value) pairs live directly inside self.window, older stream items are never retained and memory never exceeds O(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 to while 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 the while loop handles naturally in O(1) amortized time per reading! Peak space becomes O(M), where M is the largest burst of arrivals within any T-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 >= value from the back so values strictly increase) and max_window (popping <= value from the back so values strictly decrease). Each arrival enters and leaves each deque at most once, keeping overall runtime O(n) and extra space O(k).

Follow-up questions

Similar questions

More Aurora interview questions

All 5 Aurora questions →