BackmediumStackInfosysFlipkart

Monotonic Envelope Engine 7 Solution

Problem Statement

Given a complex dataset of length N representing system constraints and values, calculate the monotonic envelope using the Monotonic Stack Histogram methodology.

Example 1
Input
[5, 7, 8, 8, 8, 9, 12, 12, 12]
Output
[5, 7, 9, 12, 12]

Explanation: Step 1: Initialize an empty stack and monotonic envelope. The monotonic envelope is initialized with the first element of the input array, which is 5. Step 2: Iterate through the input array. When the current element is greater than the top of the stack, push it onto the stack and update the monotonic envelope with the current element. This is because the monotonic envelope should contain all elements, and the current element is greater than the top of the stack. Step 3: Continue iterating through the input array. When the current element is equal to the top of the stack, pop the top of the stack and update the monotonic envelope with the current element. This is because the monotonic envelope should contain all elements, and the current element is equal to the top of the stack. Step 4: Continue iterating through the input array. When the current element is less than the top of the stack, pop the top of the stack and update the monotonic envelope with the current element. This is because the monotonic envelope should contain all elements, and the current element is less than the top of the stack. Step 5: The monotonic envelope is now [5, 7, 9, 12, 12].

Example 2
Input
[1, 3, 6, 10, 15]
Output
[1, 3, 6, 10, 15]

Explanation: Step 1: Initialize an empty stack and monotonic envelope. The monotonic envelope is initialized with the first element of the input array, which is 1. Step 2: Iterate through the input array. When the current element is greater than the top of the stack, push it onto the stack and update the monotonic envelope with the current element. This is because the monotonic envelope should contain all elements, and the current element is greater than the top of the stack. Step 3: Continue iterating through the input array. When the current element is equal to the top of the stack, pop the top of the stack and update the monotonic envelope with the current element. This is because the monotonic envelope should contain all elements, and the current element is equal to the top of the stack. Step 4: Continue iterating through the input array. When the current element is less than the top of the stack, pop the top of the stack and update the monotonic envelope with the current element. This is because the monotonic envelope should contain all elements, and the current element is less than the top of the stack. Step 5: The monotonic envelope is now [1, 3, 6, 10, 15].

Constraints

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

Monotonic Envelope Engine 7 — Problem Statement & Solution Guide

StackMediumMonotonic Stack Histogram
TimeO(N)
|
SpaceO(N)

Problem Description

Given a complex dataset of length N representing system constraints and values, calculate the monotonic envelope using the Monotonic Stack Histogram methodology.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Monotonic Envelope Engine 7"

medium

WHY DOES IT MATTER?

The monotonic stack pattern reduces quadratic brute force to linear by exploiting order invariants, enabling real-time processing of large streams.

OPTIMIZATION CHALLENGE

The key insight is that once a bar is popped, its right boundary is fixed, and we never need to revisit it, so each index is pushed and popped at most once.

REAL-WORLD CONNECTION

Think of a skyline where each building’s height determines the maximum billboard area; the stack tracks the next lower building to the left and right, just like a traffic light system that only changes when a lower barrier appears.

During interviews, emphasize the amortized analysis and show a diagram of stack evolution; also mention edge cases like equal heights and how to handle them with strict vs non‑strict comparisons.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The Monotonic Envelope Engine problem is a variant of the largest rectangle in a histogram. The goal is to compute, for each position, the maximum area of a contiguous subarray where the height is bounded by the current bar and the nearest smaller bars to the left and right. A naive O(N^2) approach would examine every pair of indices, leading to quadratic time and failing for N up to 10^6. The optimal solution uses a monotonic increasing stack to keep track of indices of bars that are strictly increasing in height. When a bar of smaller height is encountered, we pop from the stack, compute the area with the popped bar as the limiting height, and update the maximum. This yields O(N) time and O(N) auxiliary space.

The stack stores indices of bars in increasing order of height. For each bar, we pop until the stack top has a height less than the current bar, ensuring that the popped bar's right boundary is the current index minus one. The left boundary is the new stack top plus one. By iterating once over the array and performing at most two pushes and pops per element, we achieve linear complexity. This pattern generalizes to many problems involving nearest smaller or greater elements, such as computing the largest rectangle in a skyline, stock span, or trapping rain water.

Because the algorithm only requires a single pass and constant-time stack operations, it scales to massive datasets and is ideal for real-time analytics in streaming systems where histogram updates must be processed on the fly.

Interview Questions on This Problem

Q1How does the monotonic stack guarantee that each element is processed in O(1) amortized time?

Each index is pushed onto the stack exactly once and popped at most once. The total number of push and pop operations across the entire array is bounded by 2N, so the average cost per element is constant, giving O(1) amortized time per element.

Q2In what scenarios would you prefer a deque over a stack for this problem?

A deque is useful when you need to support both ends, such as in sliding window maximum problems. For the largest rectangle problem, a stack suffices because we only need to pop from the top when a smaller height appears.

Q3Can you modify the algorithm to handle negative heights or missing bars?

Negative heights can be treated as zero or ignored by adding a sentinel bar of height 0 at the end. Missing bars can be represented by a sentinel value and handled by resetting the stack when encountering them.

Examples

Example 1

Input

[5, 7, 8, 8, 8, 9, 12, 12, 12]

Output

[5, 7, 9, 12, 12]

Explanation: Step 1: Initialize an empty stack and monotonic envelope. The monotonic envelope is initialized with the first element of the input array, which is 5. Step 2: Iterate through the input array. When the current element is greater than the top of the stack, push it onto the stack and update the monotonic envelope with the current element. This is because the monotonic envelope should contain all elements, and the current element is greater than the top of the stack. Step 3: Continue iterating through the input array. When the current element is equal to the top of the stack, pop the top of the stack and update the monotonic envelope with the current element. This is because the monotonic envelope should contain all elements, and the current element is equal to the top of the stack. Step 4: Continue iterating through the input array. When the current element is less than the top of the stack, pop the top of the stack and update the monotonic envelope with the current element. This is because the monotonic envelope should contain all elements, and the current element is less than the top of the stack. Step 5: The monotonic envelope is now [5, 7, 9, 12, 12].

Example 2

Input

[1, 3, 6, 10, 15]

Output

[1, 3, 6, 10, 15]

Explanation: Step 1: Initialize an empty stack and monotonic envelope. The monotonic envelope is initialized with the first element of the input array, which is 1. Step 2: Iterate through the input array. When the current element is greater than the top of the stack, push it onto the stack and update the monotonic envelope with the current element. This is because the monotonic envelope should contain all elements, and the current element is greater than the top of the stack. Step 3: Continue iterating through the input array. When the current element is equal to the top of the stack, pop the top of the stack and update the monotonic envelope with the current element. This is because the monotonic envelope should contain all elements, and the current element is equal to the top of the stack. Step 4: Continue iterating through the input array. When the current element is less than the top of the stack, pop the top of the stack and update the monotonic envelope with the current element. This is because the monotonic envelope should contain all elements, and the current element is less than the top of the stack. Step 5: The monotonic envelope is now [1, 3, 6, 10, 15].

Constraints

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

Optimal Approach & Strategy

The optimal approach uses a monotonic increasing stack to track indices of bars; each bar is pushed once and popped once, allowing us to compute the maximum rectangle area in O(N) time and O(N) auxiliary space.

Brute Force Approach

A naive solution would iterate over every pair of indices, compute the minimum height between them, and multiply by the width, leading to O(N^2) time and O(1) space.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function monotonicEnvelope(nums) {
   let stack = [];
   let monotonicEnvelope = [];
   for (let num of nums) {
       while (stack.length > 0 && stack[stack.length - 1] <= num) {
           stack.pop();
       }
       stack.push(num);
       monotonicEnvelope.push(stack[0]);
   }
   return monotonicEnvelope;
}

Asked in Top Tech Interviews

InfosysFlipkart

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.