BackmediumStackPayPalRazorpay

Monotonic Envelope Protocol 5 Solution

Problem Statement

You are tasked with analyzing a sequence of integer values representing the heights of vertical bars in a contiguous array. The objective is to compute the total area of the largest rectangle that can be formed within the histogram defined by these bars. The rectangle must be aligned with the x-axis and its height is determined by the shortest bar within its span.

Given an array heights of length N, where each element heights[i] denotes the height of the bar at index i, determine the maximum possible area of a rectangle contained within the histogram. The width of the rectangle is the number of consecutive bars included in the span, and the height is the minimum value among those bars.

Return the maximum area as an integer. If the array is empty, return 0.

Example 1
Input
heights = [2, 1, 5, 6, 2, 3]
Output
10

Explanation: The bars are [2, 1, 5, 6, 2, 3]. The largest rectangle is formed by the bars at indices 2 and 3 (values 5 and 6). The minimum height is 5, and the width is 2, giving an area of 5 * 2 = 10. Other combinations yield smaller areas: index 0-1 (min 1, width 2, area 2), index 2-5 (min 2, width 4, area 8), etc.

Example 2
Input
heights = [3, 3, 3, 3]
Output
12

Explanation: All bars have height 3. The entire array forms a rectangle of width 4 and height 3. Area = 3 * 4 = 12. No other combination yields a larger area.

Example 3
Input
heights = [1, 2, 3, 4, 5]
Output
9

Explanation: The bars are increasing. The largest rectangle is formed by the last three bars (indices 2, 3, 4) with values 3, 4, 5. The minimum height is 3, and the width is 3, giving an area of 3 * 3 = 9. Alternatively, the last two bars (4, 5) give 4 * 2 = 8, which is smaller.

Example 4
Input
heights = [5, 4, 3, 2, 1]
Output
9

Explanation: The bars are decreasing. The largest rectangle is formed by the first three bars (indices 0, 1, 2) with values 5, 4, 3. The minimum height is 3, and the width is 3, giving an area of 3 * 3 = 9. The first two bars give 4 * 2 = 8, which is smaller.

Constraints

  • 1 <= heights.length <= 10^5
  • 0 <= heights[i] <= 10^9
  • The answer is guaranteed to fit in a 64-bit integer.
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 Protocol 5 — Problem Statement & Solution Guide

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

Problem Description

You are tasked with analyzing a sequence of integer values representing the heights of vertical bars in a contiguous array. The objective is to compute the total area of the largest rectangle that can be formed within the histogram defined by these bars. The rectangle must be aligned with the x-axis and its height is determined by the shortest bar within its span.

Given an array heights of length N, where each element heights[i] denotes the height of the bar at index i, determine the maximum possible area of a rectangle contained within the histogram. The width of the rectangle is the number of consecutive bars included in the span, and the height is the minimum value among those bars.

Return the maximum area as an integer. If the array is empty, return 0.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Monotonic Envelope Protocol 5"

medium

WHY DOES IT MATTER?

Monotonic stack patterns turn seemingly quadratic range‑minimum problems into linear scans, a skill that appears repeatedly in interval, skyline, and stock‑span questions across interviews.

OPTIMIZATION CHALLENGE

The key insight is that each bar's influence ends exactly at the next smaller bar on either side, so tracking only indices of increasing heights lets us compute those boundaries without revisiting elements.

REAL-WORLD CONNECTION

Think of a river dam system where each gate height limits water flow; the stack instantly identifies the furthest upstream and downstream gates that constrain flow for any given gate, analogous to computing maximal water volume.

During coding, push indices, not heights, onto the stack; this lets you calculate widths directly and avoids off‑by‑one errors when the stack empties.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The Largest Rectangle in a Histogram problem can be modeled as finding, for each bar, the maximal width over which it remains the minimum height. A naive scan for each bar would require expanding left and right until a shorter bar is encountered, leading to O(N^2) time on worst‑case monotonic sequences. The optimal solution leverages a monotonic increasing stack to maintain indices of bars with non‑decreasing heights; when a lower height appears, the stack unwinds, instantly revealing the exact span where the popped bar is the shortest. This yields a linear pass because each index is pushed and popped at most once, guaranteeing O(N) time and O(N) auxiliary space.

The monotonic stack embodies the "divide‑and‑conquer via boundaries" paradigm: each bar's left boundary is the previous smaller element, and its right boundary is the next smaller element. By pre‑computing these boundaries in a single sweep, we avoid redundant comparisons. This approach also generalizes to other range‑minimum queries and skyline‑type problems, making it a cornerstone technique in computational geometry and data‑structure‑driven interview problems.

Interview Questions on This Problem

Q1How would you modify the algorithm to also return the coordinates (left, right) of the maximum‑area rectangle?

While popping from the stack, compute the area using the popped height and the current index as the right boundary; the left boundary is the new stack top + 1 (or 0 if the stack is empty). Keep track of the maximum area and store its left and right indices whenever a larger area is found.

Q2Can the Largest Rectangle in Histogram be solved using divide‑and‑conquer in O(N log N)? How does its performance compare to the stack method?

Yes, recursively find the minimum bar, compute the area using the whole range, and solve left/right sub‑arrays; this yields O(N log N) on average but degrades to O(N^2) for already sorted heights. The monotonic stack is strictly better with guaranteed O(N) time.

Q3In a streaming scenario where bars are appended one‑by‑one, how would you maintain the current maximum rectangle efficiently?

Maintain the same monotonic stack; each new bar is processed like the static algorithm, updating the maximum area on the fly. If deletions from the front are required, a deque or segment tree can be combined to support sliding‑window queries.

Examples

Example 1

Input

heights = [2, 1, 5, 6, 2, 3]

Output

10

Explanation: The bars are [2, 1, 5, 6, 2, 3]. The largest rectangle is formed by the bars at indices 2 and 3 (values 5 and 6). The minimum height is 5, and the width is 2, giving an area of 5 * 2 = 10. Other combinations yield smaller areas: index 0-1 (min 1, width 2, area 2), index 2-5 (min 2, width 4, area 8), etc.

Example 2

Input

heights = [3, 3, 3, 3]

Output

12

Explanation: All bars have height 3. The entire array forms a rectangle of width 4 and height 3. Area = 3 * 4 = 12. No other combination yields a larger area.

Example 3

Input

heights = [1, 2, 3, 4, 5]

Output

9

Explanation: The bars are increasing. The largest rectangle is formed by the last three bars (indices 2, 3, 4) with values 3, 4, 5. The minimum height is 3, and the width is 3, giving an area of 3 * 3 = 9. Alternatively, the last two bars (4, 5) give 4 * 2 = 8, which is smaller.

Example 4

Input

heights = [5, 4, 3, 2, 1]

Output

9

Explanation: The bars are decreasing. The largest rectangle is formed by the first three bars (indices 0, 1, 2) with values 5, 4, 3. The minimum height is 3, and the width is 3, giving an area of 3 * 3 = 9. The first two bars give 4 * 2 = 8, which is smaller.

Constraints

  • 1 <= heights.length <= 10^5
  • 0 <= heights[i] <= 10^9
  • The answer is guaranteed to fit in a 64-bit integer.

Optimal Approach & Strategy

Use a monotonic increasing stack to find next‑smaller and previous‑smaller boundaries in one linear pass, calculating areas on the fly for O(N) time and O(N) space.

Brute Force Approach

For each bar, expand left and right until a shorter bar is found, compute the area, and keep the maximum; this requires O(N^2) time in the worst case.

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[stack.length - 1]);
      }
      return monotonicEnvelope;
   }

Asked in Top Tech Interviews

PayPalRazorpay

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.