BackmediumStackAmazonCred

Optimal Grid Path Engine Solution

Problem Statement

Optimal Grid Path Engine

You are given a one‑dimensional array of non‑negative integers, where each element represents the height of a vertical column in a grid. A rectangle is defined by choosing a contiguous block of columns and taking the minimum height among them as the rectangle’s height; the width of the rectangle is the number of chosen columns. Your task is to determine the maximum possible area of such a rectangle.

The input consists of a single line containing the integer N (the number of columns) followed by N space‑separated integers h1, h2, …, hN. The output should be a single integer: the maximum rectangle area that can be formed.

The problem can be solved efficiently in linear time using a monotonic stack that keeps track of column indices with increasing heights. When a lower height is encountered, the stack is popped to compute areas of rectangles that end at the current index.

The solution must run in O(N) time and O(N) auxiliary space.

Example 1
Input
6 2 1 5 6 2 3
Output
10

Explanation: The largest rectangle uses columns 3 and 4 (heights 5 and 6). The minimum height in this block is 5, width is 2, area = 5*2 = 10. No other contiguous block yields a larger area.

Example 2
Input
2 2 4
Output
4

Explanation: Two possible rectangles: column 1 alone (area 2), column 2 alone (area 4), or both columns together (minimum height 2, width 2, area 4). The maximum is 4.

Example 3
Input
7 6 2 5 4 5 1 6
Output
12

Explanation: The optimal rectangle spans columns 3 to 5 (heights 5,4,5). Minimum height = 4, width = 3, area = 12. No other contiguous block gives a larger area.

Example 4
Input
4 1 1 1 1
Output
4

Explanation: All columns have height 1. The rectangle covering all four columns has area 1*4 = 4, which is the maximum.

Constraints

  • 1 <= N <= 100000
  • 0 <= hi <= 1000000000
  • The sum of all hi does not exceed 1000000000
  • Input is given in a single line after 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

Optimal Grid Path Engine — Problem Statement & Solution Guide

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

Problem Description

Optimal Grid Path Engine

You are given a one‑dimensional array of non‑negative integers, where each element represents the height of a vertical column in a grid. A rectangle is defined by choosing a contiguous block of columns and taking the minimum height among them as the rectangle’s height; the width of the rectangle is the number of chosen columns. Your task is to determine the maximum possible area of such a rectangle.

The input consists of a single line containing the integer N (the number of columns) followed by N space‑separated integers h1, h2, …, hN. The output should be a single integer: the maximum rectangle area that can be formed.

The problem can be solved efficiently in linear time using a monotonic stack that keeps track of column indices with increasing heights. When a lower height is encountered, the stack is popped to compute areas of rectangles that end at the current index.

The solution must run in O(N) time and O(N) auxiliary space.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Optimal Grid Path Engine"

medium

WHY DOES IT MATTER?

Monotonic stacks provide a linear-time solution to problems that involve nearest smaller or greater elements, which is essential for performance-critical applications like real-time analytics or large-scale data processing.

OPTIMIZATION CHALLENGE

The challenge is to avoid re-scanning the array for each bar; by storing indices in a stack, we can retrieve the nearest smaller bar in constant time, reducing the overall complexity from quadratic to linear.

REAL-WORLD CONNECTION

Think of a skyline where each building’s height is a bar; the stack helps quickly determine how far a building’s shadow extends before a taller building blocks it, analogous to calculating coverage areas in network signal propagation.

When explaining the algorithm, emphasize that the stack’s invariant (increasing heights) guarantees that each pop corresponds to a rectangle whose height is the popped bar, and that the width is determined by the indices surrounding the pop.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The problem is a classic instance of the "Largest Rectangle in a Histogram" problem. A naive solution examines every possible contiguous subarray, computes its minimum height, and multiplies by its width, leading to an O(n^2) time complexity and O(1) space. This quadratic approach quickly becomes infeasible for large inputs (e.g., n=10^5) because it requires nested loops and repeated scans to find minima.

The optimal solution leverages a monotonic increasing stack to process each bar exactly once. By maintaining indices of bars in ascending height order, we can determine for each bar the furthest left and right boundaries where it remains the minimum. When a bar is popped from the stack, its height is the limiting factor for a rectangle spanning from the previous stack element +1 to the current index -1. This yields an O(n) time algorithm with O(n) auxiliary space for the stack.

The key insight is that the minimum height of a rectangle is always one of the bar heights, and the maximal rectangle for a given bar can be found by knowing the nearest smaller bar to its left and right. The stack allows us to compute these boundaries in linear time, avoiding redundant comparisons and ensuring that each bar is pushed and popped at most once.

Interview Questions on This Problem

Q1How would you modify the stack-based algorithm if the histogram heights could be negative or zero?

The algorithm remains unchanged because the stack only relies on relative ordering of heights. Negative or zero heights are treated like any other value; the stack will correctly identify boundaries where a bar is smaller. However, if negative heights are allowed, the maximum area could be zero or negative, so you might need to handle the case where all heights are negative by returning 0 or the least negative area depending on problem constraints.

Q2A fintech platform asks: "Can you explain how this algorithm would scale in a distributed system where the histogram is split across multiple nodes?"

In a distributed setting, each node can compute local left/right boundaries for its segment using a stack. To merge results, nodes exchange boundary heights with neighbors to adjust the global left/right limits. The overall complexity remains linear in the total number of bars, but communication overhead must be minimized by sending only boundary indices and heights.

Q3During a high-growth startup interview, you’re asked: "What is the worst-case space complexity of the stack approach and how can you reduce it?"

The worst-case space complexity is O(n) when the histogram is strictly increasing, causing all indices to be stored. To reduce space, you can use a single array to store the stack indices and reuse it across iterations, or apply a divide-and-conquer approach that uses O(log n) stack space but still achieves O(n) time.

Examples

Example 1

Input

6
2 1 5 6 2 3

Output

10

Explanation: The largest rectangle uses columns 3 and 4 (heights 5 and 6). The minimum height in this block is 5, width is 2, area = 5*2 = 10. No other contiguous block yields a larger area.

Example 2

Input

2
2 4

Output

4

Explanation: Two possible rectangles: column 1 alone (area 2), column 2 alone (area 4), or both columns together (minimum height 2, width 2, area 4). The maximum is 4.

Example 3

Input

7
6 2 5 4 5 1 6

Output

12

Explanation: The optimal rectangle spans columns 3 to 5 (heights 5,4,5). Minimum height = 4, width = 3, area = 12. No other contiguous block gives a larger area.

Example 4

Input

4
1 1 1 1

Output

4

Explanation: All columns have height 1. The rectangle covering all four columns has area 1*4 = 4, which is the maximum.

Constraints

  • 1 <= N <= 100000
  • 0 <= hi <= 1000000000
  • The sum of all hi does not exceed 1000000000
  • Input is given in a single line after N

Optimal Approach & Strategy

Use a monotonic increasing stack to find, for each bar, the nearest smaller bar on both sides. Compute area for each bar as height * (rightIndex - leftIndex - 1). This runs in O(n) time and O(n) space.

Brute Force Approach

Check every possible subarray, find its minimum height, multiply by width, and keep the maximum. This takes O(n^2) time and constant space.

Verified Code Solutions

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

Asked in Top Tech Interviews

AmazonCred

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.