Push the sentinelAfter the pop loop, the implementation pushes (0,0). It contributes no area but leaves the loop transition fully represented.
201152632435scan0 sentinel6
unresolved stack0: height 0top →
actionpush (0,0)best10
stack
[]→[0: height 0]
action
not shown→push (0,0)
current
sentinel height 0→not shown
Return the largest closed areaEvery bar has now met its first shorter right boundary. The largest recorded rectangle has height 5, width 2, and area 10.
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?
Sources and provenance
Full interview answer 19 min read
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
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
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.
scan2011526324350 sentinel6
unresolved stackemptytop →
currentindex 0, height 2best0
stack
[]
scan
0
sentinel
6
Push height 2Nothing taller is waiting, so push (start 0, height 2).
scan2011526324350 sentinel6
unresolved stack0: height 2top →
actionpush (0,2)best0
stack
[]→[0: height 2]
action
not shown→push (0,2)
current
index 0, height 2→not shown
Height 1 closes height 2At index 1, 2 > 1, so pop (0,2): area = 2 * (1 - 0) = 2. Carry start = 0 for the shorter bar.
Push the sentinelAfter the pop loop, the implementation pushes (0,0). It contributes no area but leaves the loop transition fully represented.
201152632435scan0 sentinel6
unresolved stack0: height 0top →
actionpush (0,0)best10
stack
[]→[0: height 0]
action
not shown→push (0,0)
current
sentinel height 0→not shown
Return the largest closed areaEvery bar has now met its first shorter right boundary. The largest recorded rectangle has height 5, width 2, and area 10.
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:O(n) time and O(n) space.
Each candidate is pushed and popped at most once; heights + [0] also copies O(n) 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.