Skip to content
mlmentorship

Largest Rectangle in Histogram

Find the largest rectangle that fits under histogram bars.

Published · 19 min read ·Specialist ·Advanced

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Largest Rectangle in Histogram

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A list heights of nonnegative integer bar heights, with adjacent bars each having width one. Output. Return the largest area of an axis-aligned rectangle fully contained under the histogram. Rules. A rectangle spans consecutive bars; its height cannot exceed the shortest included bar. The bars have no horizontal gaps. Equal heights and zero-height bars are allowed. Do not modify the list. Empty input returns zero. Example. [2, 1, 5, 6, 2, 3] returns 10. The bars at indices 2 and 3 support a rectangle of width 2 and height 5.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Keep increasing (start,height) candidates; the first shorter bar closes each taller candidate at its exact maximal width.

Problem trace

A shorter bar closes spans; the zero sentinel remains on the actual stack

Input and goalFind the largest rectangle that fits under histogram bars.
Initialize the increasing stackStart with an empty stack and best=0. A final zero sentinel closes positive candidates.
unresolved stackemptytop →
currentindex 0, height 2best0
stack
[]
scan
0
sentinel
6

Recognize it
Use it when each element needs the widest contiguous span for which it remains the limiting minimum, and the first smaller boundary finalizes that span.
Keep true
Stack heights are nondecreasing; each pair (start,height) can extend from start through index-1, and every popped height receives index as its first smaller right boundary while propagating its start to the incoming shorter bar.
Reuse it
When the first violating element determines an unresolved candidate’s right boundary, keep candidates monotone and finalize them in reverse order; propagate the oldest valid start across every pop.
Start with an empty stack and best=0. A final zero sentinel closes positive candidates. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does popping height 5 at index 4 give width 4-2=2? What remains on the actual stack after the sentinel is pushed?
Full interview answer 19 min read
Reading depth

Find the greatest rectangular area that fits entirely beneath a row of histogram bars.

Problem

Input. A list heights of nonnegative integer bar heights, with adjacent bars each having width one.

Output. Return the largest area of an axis-aligned rectangle fully contained under the histogram.

Rules. A rectangle spans consecutive bars; its height cannot exceed the shortest included bar. The bars have no horizontal gaps. Equal heights and zero-height bars are allowed. Do not modify the list. Empty input returns zero.

Example. [2, 1, 5, 6, 2, 3] returns 10. The bars at indices 2 and 3 support a rectangle of width 2 and height 5.

Picture

In [2,1,5,6,2,3], reaching height 2 closes height 6 at width one, then height 5 at width two. The latter area is 10. The new height inherits the earliest popped start.

Problem trace

Separate short histogram: the real zero sentinel remains

Worked example: a shorter bar closes spans but the zero sentinel remainsAfter heights (2,1,2) and a zero sentinel, positive spans are resolved. The actual stack still retains the zero sentinel; it is not an empty stack.The final zero resolves positivespans but remains on the stack2120Best area three; no unresolvedpositive heights.0Actual stack: one retainedzero-sentinel entry.
Read it this way: After heights (2,1,2) and a zero sentinel, positive spans are resolved. The actual stack still retains the zero sentinel; it is not an empty stack. Does resolving every positive-height rectangle mean the actual stack has no entries?
Reference drawing

Problem trace

A shorter bar closes spans; the zero sentinel remains on the actual stack

Worked example: a shorter bar closes spans but the zero sentinel remainsAfter heights (2,1,2) and a zero sentinel, positive spans are resolved. The actual stack still retains the zero sentinel; it is not an empty stack.The final zero resolves positivespans but remains on the stack2120Best area three; no unresolvedpositive heights.0Actual stack: one retainedzero-sentinel entry.
Execution trace
Input and goalFind the largest rectangle that fits under histogram bars.
Initialize the increasing stackStart with an empty stack and best=0. A final zero sentinel closes positive candidates.
unresolved stackemptytop →
currentindex 0, height 2best0
stack
[]
scan
0
sentinel
6

Recognize it
Use it when each element needs the widest contiguous span for which it remains the limiting minimum, and the first smaller boundary finalizes that span.
Keep true
Stack heights are nondecreasing; each pair (start,height) can extend from start through index-1, and every popped height receives index as its first smaller right boundary while propagating its start to the incoming shorter bar.
Reuse it
When the first violating element determines an unresolved candidate’s right boundary, keep candidates monotone and finalize them in reverse order; propagate the oldest valid start across every pop.
Start with an empty stack and best=0. A final zero sentinel closes positive candidates. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does popping height 5 at index 4 give width 4-2=2? What remains on the actual stack after the sentinel is pushed?
Read it this way: After heights (2,1,2) and a zero sentinel, positive spans are resolved. The actual stack still retains the zero sentinel; it is not an empty stack. Does resolving every positive-height rectangle mean the actual stack has no entries?

Stack heights are nondecreasing, not strictly increasing: the literal > comparison retains equal heights. Each saved start extends left across already-cleared taller bars. The first shorter right bar prevents further extension at that height. An appended zero finalizes every positive-height candidate.

Code

def largest_rectangle_area(heights: list[int]) -> int:
   stack: list[tuple[int, int]] = []
   best = 0

   for index, height in enumerate(heights + [0]):
      start = index
      while stack and stack[-1][1] > height:
         start, old_height = stack.pop()
         best = max(best, old_height * (index - start))
      stack.append((start, height))

   return best

Cost: time and space.

Each candidate is pushed and popped at most once; heights + [0] also copies references. Bounds count scalar operations, not integer bit costs.

Change the Requirement

Return a Rectangle Witness

New task: Return (area, left, right_exclusive, height).

Picture and change: Save each strictly better popped rectangle, not only its area.

Code: This complete variant uses a virtual sentinel without copying the input.

def largest_rectangle_witness(heights: list[int]):
   stack = []
   best = (0, 0, 0, 0)
   for index in range(len(heights) + 1):
      height = heights[index] if index < len(heights) else 0
      start = index
      while stack and stack[-1][1] > height:
         start, old_height = stack.pop()
         area = old_height * (index - start)
         if area > best[0]:
            best = (area, start, index, old_height)
      stack.append((start, height))
   return best

Check: [2,1,2] returns (3,0,3,1); equal-area ties retain the first strict improvement.

Use when: A caller needs boundaries; time and workspace stay linear.

Give Bars Unequal Widths

New task: Accept a positive integer width per bar.

Picture and change: Carry physical left coordinates; replace index differences with coordinate differences.

Code: Heights retain the nonnegative-integer contract.

def largest_weighted_rectangle(heights: list[int], widths: list[int]) -> int:
   if len(heights) != len(widths) or any(width <= 0 for width in widths):
      raise ValueError("each bar needs one positive width")
   stack, best, position = [], 0, 0
   for index in range(len(heights) + 1):
      height = heights[index] if index < len(heights) else 0
      start = position
      while stack and stack[-1][1] > height:
         start, old_height = stack.pop()
         best = max(best, old_height * (position - start))
      stack.append((start, height))
      if index < len(heights):
         position += widths[index]
   return best

Check: Heights [2,1,2] and widths [2,1,2] yield 5, not the unit-width answer 3.

Use when: Bars occupy unequal horizontal spans. The same push/pop argument gives linear time and workspace.

Reconstruct

What breaks if a popped start is discarded?

Reasoned answer

For [3,2,2], the height-two rectangle starts at zero and spans all three bars, giving area six. Restarting it at index one loses that valid left extension. Equal-height duplicates may remain; they do not invalidate the inherited earliest boundary.