BackeasyHeapWiproZomato

Segmented Capacity Window Solution

Problem Statement

You are given an array nums of integers representing the load capacity at discrete time steps. The system processes these values using a sliding window of fixed size k. For every position of the window as it traverses the array from left to right, the system must determine the minimum value within that specific window. This minimum value represents the bottleneck throughput for that interval.

Your task is to return an array where each element corresponds to the minimum value observed in the window at that specific position. The window starts at index 0 and slides one step to the right until it reaches the end of the array. The total number of windows is n - k + 1, where n is the length of the array.

Implement a function that efficiently computes these minimums. While a brute-force approach would work for small inputs, you are expected to design a solution that leverages a Min-Heap to maintain the current window's elements and extract the minimum in logarithmic time relative to the window size.

Example 1
Input
nums = [4, 2, 1, 3, 5], k = 3
Output
[2, 1, 3]

Explanation: Window 1: [4, 2, 1] -> min is 2. Window 2: [2, 1, 3] -> min is 1. Window 3: [1, 3, 5] -> min is 3. Result: [2, 1, 3].

Example 2
Input
nums = [10, 10, 10, 10], k = 2
Output
[10, 10, 10]

Explanation: Window 1: [10, 10] -> min is 10. Window 2: [10, 10] -> min is 10. Window 3: [10, 10] -> min is 10. Result: [10, 10, 10].

Example 3
Input
nums = [7, 1, 8, 2, 9, 3], k = 4
Output
[1, 1, 2]

Explanation: Window 1: [7, 1, 8, 2] -> min is 1. Window 2: [1, 8, 2, 9] -> min is 1. Window 3: [8, 2, 9, 3] -> min is 2. Result: [1, 1, 2].

Example 4
Input
nums = [5], k = 1
Output
[5]

Explanation: Window 1: [5] -> min is 5. Result: [5].

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= k <= nums.length
  • -10^9 <= nums[i] <= 10^9
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Segmented Capacity Window — Problem Statement & Solution Guide

HeapEasyMin-Heap Extraction
TimeO(n log k)
|
SpaceO(k)

Problem Description

You are given an array nums of integers representing the load capacity at discrete time steps. The system processes these values using a sliding window of fixed size k. For every position of the window as it traverses the array from left to right, the system must determine the minimum value within that specific window. This minimum value represents the bottleneck throughput for that interval.

Your task is to return an array where each element corresponds to the minimum value observed in the window at that specific position. The window starts at index 0 and slides one step to the right until it reaches the end of the array. The total number of windows is n - k + 1, where n is the length of the array.

Implement a function that efficiently computes these minimums. While a brute-force approach would work for small inputs, you are expected to design a solution that leverages a Min-Heap to maintain the current window's elements and extract the minimum in logarithmic time relative to the window size.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Segmented Capacity Window"

easy

WHY DOES IT MATTER?

Sliding‑window problems appear in rate‑limiting, real‑time analytics, and signal processing. Mastering the heap‑based pattern equips engineers to handle scenarios where the window size is moderate but the cost of O(k) per step is unacceptable.

OPTIMIZATION CHALLENGE

The key insight is lazy deletion: instead of removing stale elements immediately (which would require O(k) search), we simply ignore them when they surface at the heap top, keeping all operations at O(log k).

REAL-WORLD CONNECTION

Think of a network router that keeps the smallest packet latency observed over the last k seconds to detect congestion. As new packets arrive, the router pushes their latency into a priority queue and discards latencies older than k seconds, always exposing the current bottleneck.

During an interview, insert (value, index) into the heap, then before reading the minimum, pop while heap[0].index <= i‑k. This one‑liner keeps the code clean and avoids extra data structures.

COMPLEXITY AT A GLANCE

⏱ Time:O(n log k)
💾 Space:O(k)

Core Theory — Why This Approach?

The sliding‑window minimum problem asks for the smallest element in every contiguous sub‑array of length k. A naïve scan of each window costs O(k) per position, leading to O(n·k) time, which is prohibitive when n and k are large (e.g., n up to 10^6). The optimal paradigm leverages a data structure that can both retrieve the current minimum quickly and discard elements that fall out of the window. A min‑heap naturally supports O(log k) insertion and extraction of the smallest element, but it cannot delete arbitrary stale entries in constant time. The trick is to store pairs (value, index) in the heap and lazily discard entries whose index is outside the current window whenever the top of the heap is examined. This yields an overall O(n log k) solution, which is fast enough for typical constraints and aligns with the “heap‑based sliding window” pattern.

An alternative O(n) solution uses a monotonic deque, but the heap approach is valuable because it generalizes to problems where the ordering criterion is more complex (e.g., maintaining the k‑largest sums, or handling dynamic updates). Understanding the lazy‑deletion technique also deepens knowledge of how priority queues can be adapted for sliding‑window scenarios, a skill frequently tested in system‑design and performance‑critical coding interviews.

Interview Questions on This Problem

Q1How would you modify the heap‑based sliding window algorithm to return the maximum value in each window instead of the minimum?

Replace the min‑heap with a max‑heap (or store negative values in a min‑heap). The rest of the algorithm stays the same: push (value, index) pairs, and lazily discard entries whose index is out of range when peeking at the top.

Q2Can you achieve O(n) time for the sliding window minimum using a heap? Why or why not?

No, a heap inherently incurs O(log k) per insertion or removal, so the total time is O(n log k). Achieving O(n) requires a different data structure, such as a monotonic deque, which maintains a sorted order of candidates without the logarithmic overhead.

Q3In a distributed system that processes time‑series metrics, why might a heap‑based sliding window be preferred over a deque‑based one?

When each node processes a subset of the stream and needs to merge partial results, a heap can efficiently combine the minima from multiple partitions (e.g., via a min‑heap of window minima). A deque is tied to a single linear order and does not support easy merging of independent windows.

Examples

Example 1

Input

nums = [4, 2, 1, 3, 5], k = 3

Output

[2, 1, 3]

Explanation: Window 1: [4, 2, 1] -> min is 2. Window 2: [2, 1, 3] -> min is 1. Window 3: [1, 3, 5] -> min is 3. Result: [2, 1, 3].

Example 2

Input

nums = [10, 10, 10, 10], k = 2

Output

[10, 10, 10]

Explanation: Window 1: [10, 10] -> min is 10. Window 2: [10, 10] -> min is 10. Window 3: [10, 10] -> min is 10. Result: [10, 10, 10].

Example 3

Input

nums = [7, 1, 8, 2, 9, 3], k = 4

Output

[1, 1, 2]

Explanation: Window 1: [7, 1, 8, 2] -> min is 1. Window 2: [1, 8, 2, 9] -> min is 1. Window 3: [8, 2, 9, 3] -> min is 2. Result: [1, 1, 2].

Example 4

Input

nums = [5], k = 1

Output

[5]

Explanation: Window 1: [5] -> min is 5. Result: [5].

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= k <= nums.length
  • -10^9 <= nums[i] <= 10^9

Optimal Approach & Strategy

Maintain a min‑heap of (value, index) pairs, lazily discarding out‑of‑range entries when accessing the top, achieving O(n log k) time.

Brute Force Approach

For each window, scan all k elements to find the minimum, resulting in O(n·k) time.

Verified Code Solutions

JavaScript Solution
Time: O(n log k)
function solution(nums) {
               let sum = 0;
               for (let num of nums) {
                 sum += num;
               }
               return sum;
             }

Asked in Top Tech Interviews

WiproZomato

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.