BackeasyGreedyAccentureSwiggy

Calculated Stack Horizon Solution

Problem Statement

You are given an array or sequence of length $N$ representing numerical values or system metrics. Your task is to compute the calculated stack horizon according to the target algorithm rules.

Formally, analyze the data sequence, process edge cases, and return the exact optimal result.

Example 1
Input
[4, 7, 10, 13]
Output
34

Explanation: Step-by-step: with input [4, 7, 10, 13], we first calculate the sum of the array elements, which is 4 + 7 + 10 + 13 = 34. Then, we return the sum as the calculated stack horizon.

Example 2
Input
[4, 8]
Output
12

Explanation: Step-by-step: with input [4, 8], we first calculate the sum of the array elements, which is 4 + 8 = 12. Then, we return the sum as the calculated stack horizon.

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

Calculated Stack Horizon — Problem Statement & Solution Guide

GreedyEasyPriority Crate Allocation
TimeO(N)
|
SpaceO(N)

Problem Description

You are given an array or sequence of length $N$ representing numerical values or system metrics. Your task is to compute the calculated stack horizon according to the target algorithm rules.

Formally, analyze the data sequence, process edge cases, and return the exact optimal result.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Calculated Stack Horizon"

easy

WHY DOES IT MATTER?

Monotonic stack patterns appear in many real‑time analytics, such as computing stock spans, daily temperatures, and histogram rectangle areas. Mastering this pattern equips engineers to turn seemingly quadratic scans into linear passes, a critical skill for high‑throughput systems.

OPTIMIZATION CHALLENGE

The key insight is to discard elements that can never become a horizon for any future index. By maintaining a stack where values are strictly monotonic, you ensure that once an element is popped it will never be needed again, collapsing the double loop into a single linear sweep.

REAL-WORLD CONNECTION

Imagine a server monitoring dashboard that needs to show, for each minute, how many consecutive previous minutes the CPU usage stayed below the current level. Using a monotonic stack, the system can update this metric in O(1) per minute, enabling real‑time alerts without costly recomputation.

When coding the solution, always store indices—not values—in the stack. This lets you compute the exact distance (i - stack.peek()) for the horizon and avoids extra array lookups, keeping the code clean and bug‑free.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
đź’ľ Space:O(N)

Core Theory — Why This Approach?

The Calculated Stack Horizon problem is a classic example of using a monotonic stack to achieve a greedy solution in linear time. The goal is to determine, for each position in the array, how far back you can look while maintaining a non‑decreasing (or non‑increasing) relationship, which translates to the “horizon” of each element. A naive double‑loop that scans leftwards for every index would be O(N²) and quickly exceeds time limits for large N because each element may be revisited many times. By maintaining a stack that stores indices of elements in a monotonic order, we can pop elements that are no longer useful for future queries, guaranteeing each element is pushed and popped at most once. This greedy removal of dominated candidates yields an optimal O(N) algorithm while using O(N) auxiliary space for the stack.

Interview Questions on This Problem

Q1How would you modify the monotonic stack solution if the horizon must be computed for a non‑decreasing sequence instead of a non‑increasing one?

Flip the comparison direction in the while loop: while (!stack.isEmpty() && arr[stack.peek()] <= arr[i]) pop. This keeps the stack monotonic decreasing, allowing you to count how many previous elements are less than or equal to the current value.

Q2Can the Calculated Stack Horizon be solved in O(1) extra space? If so, under what constraints?

Only if the input can be overwritten and you can reuse the array itself as a stack, effectively achieving O(1) auxiliary space. This works when you don't need to preserve the original array and can store intermediate indices or counts directly in the array.

Q3Why does the monotonic stack guarantee each element is processed at most twice, and how does that affect the overall time complexity?

Each element is pushed onto the stack exactly once. It may later be popped when a larger (or smaller, depending on the variant) element appears. Since push and pop are O(1) operations and each element participates in at most one push and one pop, the total work across the entire array is O(N).

Examples

Example 1

Input

[4, 7, 10, 13]

Output

34

Explanation: Step-by-step: with input [4, 7, 10, 13], we first calculate the sum of the array elements, which is 4 + 7 + 10 + 13 = 34. Then, we return the sum as the calculated stack horizon.

Example 2

Input

[4, 8]

Output

12

Explanation: Step-by-step: with input [4, 8], we first calculate the sum of the array elements, which is 4 + 8 = 12. Then, we return the sum as the calculated stack horizon.

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

Maintain a decreasing monotonic stack of indices; for each i, pop while arr[stack.top] <= arr[i], then horizon = i - stack.top (or i+1 if stack empty), and push i.

Brute Force Approach

For each index i, scan leftwards until you find a larger element, counting steps; repeat for all i.

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

AccentureSwiggy

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.