BackmediumRecursionMicrosoftRazorpay

Resilient 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 resilient 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
[9, 2, 5, 8]
Output
24

Explanation: Step-by-step: Given the input array [9, 2, 5, 8], we iterate through each element and sum them up. The sum of 9 + 2 + 5 + 8 is 24.

Example 2
Input
[4, 8]
Output
12

Explanation: Step-by-step: Given the input array [4, 8], we iterate through each element and sum them up. The sum of 4 + 8 is 12.

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

Resilient Stack Horizon — Problem Statement & Solution Guide

RecursionMediumBacktracking Path
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 resilient 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

"Resilient Stack Horizon"

medium

WHY DOES IT MATTER?

Monotonic‑stack patterns appear in any scenario where you need to answer “how far can I see until a larger barrier appears?” – from stock‑price analysis to memory‑allocation fragmentation, making it a core tool for performance‑critical metric processing.

OPTIMIZATION CHALLENGE

The breakthrough is recognizing that each element’s horizon can be expressed as a sum of distances to the next taller element, allowing us to “jump” over blocks of smaller elements in O(1) amortized time using a stack, reducing the naïve O(N²) scan to O(N).

REAL-WORLD CONNECTION

Imagine a network of sensors placed along a pipeline; each sensor reports pressure. The horizon for a sensor is the distance to the next sensor reporting a higher pressure, which determines where alarms propagate. Computing this efficiently ensures real‑time monitoring without flooding the control system.

When coding, push indices onto the stack, not values; this lets you compute distances directly and also retrieve the blocker index if needed. Always clear the stack at the end of each test case to avoid cross‑test contamination.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(N)

Core Theory — Why This Approach?

The Resilient Stack Horizon problem asks you to scan a numeric sequence and, for each position, determine how far the “view” extends before a larger value blocks the line of sight – essentially a variant of the classic stock‑span or skyline horizon problem. A naïve solution would recompute the horizon for every index by walking leftwards until a higher value is found, leading to O(N²) time on monotonic inputs. The optimal paradigm leverages the recursive nature of the horizon: the horizon for index i can be expressed in terms of the horizon for the previous index that is strictly higher. By maintaining a monotonic decreasing stack (or using recursion with memoization) we can collapse these dependencies in a single pass, achieving linear time while preserving the exact span lengths.

Recursion shines here because each element’s answer depends on the answer of the next taller element to its left. By recursively querying that taller element’s horizon and adding the distance, we avoid repeated scans. The stack implementation is merely an iterative embodiment of this recursion, guaranteeing O(N) time and O(N) auxiliary space in the worst case (when the sequence is strictly decreasing). This approach scales to massive inputs where the naïve quadratic method would time‑out or exhaust stack frames.

The key insight is that the horizon forms a nested structure: a smaller element’s view is always a subset of the view of the next larger element to its left. Recognizing this nesting allows us to compress the problem into a series of “jump” operations, each resolved in constant amortized time, which is the hallmark of many monotonic‑stack problems in competitive programming and system‑level metric analysis.

Interview Questions on This Problem

Q1How would you adapt the Resilient Stack Horizon solution to also return the index of the blocking element for each position?

Maintain the stack of indices; when processing element i, pop until the top holds a value > a[i]. The top index after popping is the blocker; if the stack becomes empty, the blocker is -1. Store this index alongside the computed horizon length.

Q2Can the recursive formulation be transformed into a tail‑recursive function to avoid stack overflow on very large N?

Yes. By passing the current index and the previously computed horizon as parameters, the recursion can be written in tail‑position. Most modern runtimes will then optimize it into an iterative loop, effectively mirroring the monotonic‑stack implementation.

Q3Explain how the horizon problem relates to the ‘Next Greater Element’ pattern and why the same data structure works for both.

Both problems require, for each element, the nearest larger element to its left (or right). The monotonic decreasing stack maintains candidates in order of decreasing value, guaranteeing that the top is always the next greater element for the upcoming items. Hence the same stack can answer both horizon lengths (by also storing distances) and next‑greater queries.

Examples

Example 1

Input

[9, 2, 5, 8]

Output

24

Explanation: Step-by-step: Given the input array [9, 2, 5, 8], we iterate through each element and sum them up. The sum of 9 + 2 + 5 + 8 is 24.

Example 2

Input

[4, 8]

Output

12

Explanation: Step-by-step: Given the input array [4, 8], we iterate through each element and sum them up. The sum of 4 + 8 is 12.

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 monotonic decreasing stack (or recursive jumps) to collapse those leftward walks into constant‑time operations, achieving a single linear scan.

Brute Force Approach

For each index, walk leftwards until a larger value is found, counting steps; repeat for all indices.

Verified Code Solutions

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

Asked in Top Tech Interviews

MicrosoftRazorpay

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.