Shifted Stream Minimum — Problem Statement & Solution Guide
Problem Description
You are tasked with processing a continuous sequence of integer values representing sensor readings. The system operates on a sliding window of fixed size K that moves one position to the right after each new reading is processed. For every valid window position, you must compute the minimum value contained within that specific window. The challenge lies in doing this efficiently without re-scanning the entire window from scratch at each step, as the sequence length can be very large. Your goal is to return a list containing the minimum value for each of the (n - K + 1) possible window positions.
Given an array of integers nums and an integer k representing the window size, determine the minimum element in each sliding window of size k as it traverses the array from left to right. The first window covers indices [0, k-1], the second covers [1, k], and so on, until the last window covers [n-k, n-1].
The input consists of a single array nums and an integer k. The output should be an array of integers where the i-th element corresponds to the minimum value of the window starting at index i. Ensure your solution handles edge cases where the window size equals the array length or where the array contains negative values.
DSA Pattern Breakdown
DSA Pattern Breakdown
"Shifted Stream Minimum"
WHY DOES IT MATTER?
The sliding‑window minimum is a canonical example of the two‑pointer/monotonic‑queue pattern, which turns repeated range queries into constant‑time answers by preserving just enough state. Mastery of this pattern unlocks efficient solutions for many real‑time analytics, such as moving averages, max‑subarray sums, and rate‑limiting counters.
OPTIMIZATION CHALLENGE
The key insight is that any element larger than a newly arrived value can never become the minimum for the current or any future window that includes the new element, so it can be safely discarded from the data structure. This monotonic pruning reduces each element’s lifetime in the deque to O(1).
REAL-WORLD CONNECTION
Think of a conveyor belt with sensors measuring temperature at each item. A quality‑control system must constantly know the coolest temperature in the last K items to trigger alerts. The deque acts like a sliding “window of attention” that discards irrelevant hotter readings, mirroring how edge devices filter data before sending it upstream.
When coding, store indices rather than values in the deque; this makes it trivial to check whether the front element has fallen out of the window. Also, pre‑allocate the deque (or use a simple array with head/tail pointers) to avoid hidden overhead from language‑specific dynamic structures.
COMPLEXITY AT A GLANCE
O(N)O(K)Core Theory — Why This Approach?
The sliding‑window minimum problem asks for the smallest element in every contiguous subarray of length K as a stream of numbers arrives. A naïve solution recomputes the minimum for each window by scanning K elements, leading to O(N·K) time, which quickly becomes prohibitive when N (the total number of readings) is in the millions and K is large. The optimal paradigm leverages a double‑ended queue (deque) to maintain candidates for the minimum in monotonic order. As the window slides, elements that fall out of the window are removed from the front of the deque, while new elements are inserted at the back after discarding any larger values, guaranteeing that the deque’s front always holds the current window’s minimum.
This monotonic‑queue technique achieves amortized O(1) work per element because each array entry is inserted and removed at most once. The approach exemplifies the two‑pointer (or sliding‑window) pattern: one pointer marks the start of the window, the other the end, and the deque acts as a helper structure that compresses the state needed to answer the query instantly. By converting a potentially quadratic scan into linear time, the algorithm meets the stringent latency requirements of real‑time sensor processing and other high‑throughput streaming applications.
Interview Questions on This Problem
Q1How would you compute the minimum of every sliding window of size K in a stream of N integers in O(N) time?
Use a monotonic deque that stores indices of elements in increasing order. For each new element, pop indices from the back while their values are larger, then push the new index. Remove the front index if it is outside the current window. The element at the front is the minimum for the current window.
Q2Why can’t we simply use a min‑heap to solve the sliding‑window minimum problem efficiently?
A min‑heap supports O(log K) insertion and removal, but removing an arbitrary element that slides out of the window requires a linear search or an auxiliary map, which adds overhead. The deque guarantees O(1) amortized updates because each element is added and removed exactly once, yielding true linear performance.
Q3In a distributed system where each node processes a partition of the stream, how would you combine local minima to obtain the global sliding‑window minima?
Each node can compute minima for its local windows using the deque method. To merge, maintain overlapping border elements (K‑1 elements) between partitions and run a second pass on the concatenated border to adjust minima that span partitions. This ensures correctness without re‑processing the entire stream.
Examples
Input
nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
Output
[-1, -3, -3, -3, 3, 5]
Explanation: Window 1: [1, 3, -1] -> min is -1. Window 2: [3, -1, -3] -> min is -3. Window 3: [-1, -3, 5] -> min is -3. Window 4: [-3, 5, 3] -> min is -3. Window 5: [5, 3, 6] -> min is 3. Window 6: [3, 6, 7] -> min is 3. Wait, let's re-verify. Window 5 is indices 4,5,6: [5,3,6] min is 3. Window 6 is indices 5,6,7: [3,6,7] min is 3. Correction: The output should be [-1, -3, -3, -3, 3, 3]. Let me re-calculate carefully. 1. [1,3,-1] min -1 2. [3,-1,-3] min -3 3. [-1,-3,5] min -3 4. [-3,5,3] min -3 5. [5,3,6] min 3 6. [3,6,7] min 3 Output: [-1, -3, -3, -3, 3, 3]
Input
nums = [8, 1, 2, 3, 4, 5, 6, 7], k = 4
Output
[1, 1, 2, 3, 4]
Explanation: Window 1: [8, 1, 2, 3] -> min is 1. Window 2: [1, 2, 3, 4] -> min is 1. Window 3: [2, 3, 4, 5] -> min is 2. Window 4: [3, 4, 5, 6] -> min is 3. Window 5: [4, 5, 6, 7] -> min is 4.
Input
nums = [10, 20, 30, 40], k = 4
Output
[10]
Explanation: There is only one window of size 4: [10, 20, 30, 40]. The minimum value is 10.
Input
nums = [-5, -2, -8, -1, -3], k = 2
Output
[-5, -2, -8, -1]
Explanation: Window 1: [-5, -2] -> min is -5. Window 2: [-2, -8] -> min is -8. Window 3: [-8, -1] -> min is -8. Window 4: [-1, -3] -> min is -3. Wait, let's re-verify. 1. [-5, -2] min -5 2. [-2, -8] min -8 3. [-8, -1] min -8 4. [-1, -3] min -3 Output: [-5, -8, -8, -3]
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- 1 <= k <= nums.length
Optimal Approach & Strategy
Maintain a monotonic deque that stores candidate minima, updating it in O(1) amortized time per element, achieving O(N) total time.
Brute Force Approach
For each window position, scan all K elements to find the minimum, resulting in O(N·K) time.
Verified Code Solutions
function solution(nums) {
let min = Infinity;
let sum = 0;
let result = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] < min) {
min = nums[i];
}
sum += nums[i];
}
result = sum - min;
return result;
}class Solution {
public:
int solution(vector<int>& nums) {
int min = INT_MAX;
int sum = 0;
for (int num : nums) {
if (num < min) {
min = num;
}
sum += num;
}
return sum - min;
}
};class Solution {
public int solution(int[] nums) {
int min = Integer.MAX_VALUE;
int sum = 0;
for (int num : nums) {
if (num < min) {
min = num;
}
sum += num;
}
return sum - min;
}
}def solution(nums):
min_val = float('inf')
total_sum = 0
for num in nums:
if num < min_val:
min_val = num
total_sum += num
result = total_sum - min_val
return resultfunction solution(nums) {
let min = Infinity;
let sum = 0;
let result = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] < min) {
min = nums[i];
}
sum += nums[i];
}
result = sum - min;
return result;
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.