BackmediumSliding WindowAdobeInfosys

Minimized Stack Horizon Solution

Problem Statement

Given an array or sequence of length N representing numerical values or system metrics, compute the sum of the array according to the target algorithm rules.

Example 1
Input
[1, 2, 3, 4, 5]
Output
15

Explanation: Step-by-step: with input [1, 2, 3, 4, 5], we calculate the sum of the array using a simple loop, giving output 15.

Example 2
Input
[10, 20, 30, 40, 50]
Output
150

Explanation: Step-by-step: with input [10, 20, 30, 40, 50], we calculate the sum of the array using a simple loop, giving output 150.

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity expected: O(N) or O(N log N)
  • Space Complexity expected: O(1) or O(N)
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

Minimized Stack Horizon — Problem Statement & Solution Guide

Sliding WindowMediumFixed Length Window
TimeO(N)
|
SpaceO(K) (or O(1) if only sum is required)

Problem Description

Given an array or sequence of length N representing numerical values or system metrics, compute the sum of the array according to the target algorithm rules.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Minimized Stack Horizon"

medium

WHY DOES IT MATTER?

Sliding‑window patterns turn quadratic‑time brute‑force loops into linear scans, which is crucial when processing high‑frequency metrics, log streams, or large data batches where latency and resource consumption directly impact system reliability.

OPTIMIZATION CHALLENGE

The breakthrough is recognizing that consecutive windows share N‑1 elements; by updating aggregates incrementally and using a monotonic deque to keep track of extrema, we eliminate redundant work and achieve O(N) time with O(K) (or O(1)) extra space.

REAL-WORLD CONNECTION

Think of a network router that monitors the average packet size over the last 1,000 packets to detect anomalies. Instead of recomputing the average from scratch for each new packet, the router updates the running sum as packets slide in and out, mirroring the sliding‑window technique.

During an interview, write the sliding‑window skeleton first—initialize the first window, then loop from K to N‑1 updating the aggregate. Only after the scaffold is solid, integrate the deque for min/max; this staged approach reduces bugs and showcases clear thinking.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(K) (or O(1) if only sum is required)

Core Theory — Why This Approach?

The "Minimized Stack Horizon" problem is a classic sliding‑window scenario where we must aggregate information (often a sum, minimum, or maximum) over every contiguous sub‑array of a fixed length K. A naïve solution recomputes the aggregate from scratch for each window, leading to O(N·K) time, which quickly becomes prohibitive for N up to 10^5 or higher. The optimal paradigm leverages the overlapping nature of consecutive windows: when the window slides one position to the right, only one element exits and one new element enters, allowing us to update the aggregate in constant time. This insight gives us an O(N) linear scan while using O(1) auxiliary space, a dramatic improvement that makes the algorithm scalable for real‑world telemetry streams and large‑scale data pipelines.

In many variants, the problem also asks for a secondary constraint such as keeping the window’s “horizon” – the maximum element – as low as possible. By coupling a deque (or monotonic stack) with the sliding window, we can maintain the current maximum (or minimum) in O(1) amortized time, preserving the overall linear complexity. The monotonic property ensures that each element is pushed and popped at most once, which is the key to achieving the optimal time bound while still providing the required horizon minimization.

Understanding why the naïve approach fails and how the sliding‑window + monotonic data structure works is essential for interviewers. It demonstrates mastery of two fundamental techniques—incremental aggregation and monotonic queues—that appear across a spectrum of problems, from stock‑price analysis to rate‑limiting in distributed systems.

Interview Questions on This Problem

Q1How would you compute the sum of every sub‑array of size K in O(N) time?

Initialize the sum of the first K elements, then slide the window: subtract the element leaving the window and add the new element entering it. Record the sum after each slide. This yields a linear scan with O(1) per step.

Q2Explain how a monotonic deque can be used to find the minimum (or maximum) in each sliding window.

Maintain a deque storing indices of elements in decreasing (or increasing) order. When moving the window, discard indices that fall out of range and pop from the back while the current element violates the monotonic order. The front of the deque always holds the index of the window’s minimum (or maximum), allowing O(1) retrieval per slide.

Q3Why does each element get pushed and popped at most once in a monotonic queue, and how does that guarantee O(N) total time?

Because the deque only removes elements from the back when a newer element is more extreme (larger for max, smaller for min). Once an element is removed, it never re‑enters. Hence each array element participates in at most one push and one pop, leading to O(N) amortized operations across the entire scan.

Examples

Example 1

Input

[1, 2, 3, 4, 5]

Output

15

Explanation: Step-by-step: with input [1, 2, 3, 4, 5], we calculate the sum of the array using a simple loop, giving output 15.

Example 2

Input

[10, 20, 30, 40, 50]

Output

150

Explanation: Step-by-step: with input [10, 20, 30, 40, 50], we calculate the sum of the array using a simple loop, giving output 150.

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity expected: O(N) or O(N log N)
  • Space Complexity expected: O(1) or O(N)

Optimal Approach & Strategy

Use a sliding window: keep a running sum that you update by subtracting the element that slides out and adding the new element that slides in. For min/max, maintain a monotonic deque to retrieve the extreme in O(1) per slide, achieving overall O(N) time.

Brute Force Approach

For each possible window, iterate over its K elements and compute the sum (or min/max) from scratch. This results in O(N·K) time because the inner loop runs K times for each of the N‑K+1 windows.

Verified Code Solutions

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

Asked in Top Tech Interviews

AdobeInfosys

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.