HARD NC#27 Stack - Monotonic Stack

84. Largest Rectangle in Histogram

šŸ“– Problem

Given an array of integers heights representing histogram's bar height, return the area of largest rectangle in the histogram.

🧠 Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • •Array methods (`push`, `pop`, `shift`, `slice`)
  • •Object/Map/Set usage patterns
  • •Function parameter and return typing

Logical Thinking Concepts

  • •Define invariants before coding
  • •Check edge cases first (`[]`, single element, duplicates)
  • •Estimate time/space before implementation
  • •Apply Monotonic Stack reasoning pattern

šŸ’” Approach

  • → Use monotonic increasing stack to track indices
  • → When current height < stack top, pop and calculate area
  • → For popped bar, width extends from current index to previous stack index
  • → Width = stack.empty() ? current index : current index - stack.top() - 1
  • → Add sentinel (0 height) at end to ensure all bars are processed
  • → Time: O(n), Space: O(n)

šŸ› ļø Hints & Pitfalls

Hints

  • •Use monotonic increasing stack to track indices
  • •When current height < stack top, pop and calculate area
  • •For popped bar, width extends from current index to previous stack index

Common Pitfalls

  • •Width = stack.empty() ? current index : current index - stack.top() - 1
  • •Add sentinel (0 height) at end to ensure all bars are processed
  • •Time: O(n), Space: O(n)

🧪 Test Cases

Hidden tests on submit: 2

Test Case 1
Not run
Input:
largestRectangleArea([2,1,5,6,2,3]);
Expected:
10
Test Case 2
Not run
Input:
largestRectangleArea([2,4]);
Expected:
4
Test Case 3
Not run
Input:
largestRectangleArea([1]);
Expected:
1

šŸ“ Code Editor

šŸ“š Reference Solution

ā–¼
⌘K Search āŒ˜ā†© Run ⌘S Submit