Largest rectangle in a histogram
32 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Finding the largest rectangle in a histogram is a cornerstone stack interview question. The same monotonic boundary technique solves maximal rectangles in matrices and calculates trapped rain water.
Largest rectangle in a histogram using monotonic stack
Each bar can form a rectangle of its own height, stretching left and right until a shorter bar blocks it. A monotonic increasing stack of indexes finds those blocking bars for every bar in one pass.
- Push bar index if height is greater than stack top.
- While incoming height is smaller, pop top index as
hIndex. - Compute
height = heights[hIndex]. - Compute
width = stack.isEmpty() ? i : i - stack.peek() - 1. - Update
maxArea = Math.max(maxArea, height * width).
Example 1 · Brute force: expand left and right from every bar (O(n^2) time, O(1) extra space)
public class HistogramBruteDemo { static int largestRectangleArea(int[] heights) { int best = 0; for (int i = 0; i < heights.length; i++) { int left = i; while (left > 0 && heights[left - 1] >= heights[i]) left--; int right = i; while (right < heights.length - 1 && heights[right + 1] >= heights[i]) right++; best = Math.max(best, heights[i] * (right - left + 1)); } return best; }
public static void main(String[] args) { int[] heights = {2, 1, 5, 6, 2, 3}; System.out.println("Largest rectangle: " + largestRectangleArea(heights)); }}Largest rectangle: 10
What this code does
- For bar
i,leftandrightstretch over every neighbouring bar that is at least as tall, giving the widest rectangle of heightheights[i]. - Each bar may walk across most of the array, so the total is O(n^2).
- A monotonic stack finds the same two boundaries for all bars in one pass, as shown next.
Example 2 · Optimal: monotonic stack (O(n) time, O(n) space)
import java.util.ArrayDeque;import java.util.Deque;
public class LargestRectangleHistogramDemo { public static int largestRectangleArea(int[] heights) { int n = heights.length; Deque<Integer> stack = new ArrayDeque<>(); int maxArea = 0;
for (int i = 0; i <= n; i++) { int h = (i == n) ? 0 : heights[i]; while (!stack.isEmpty() && h < heights[stack.peek()]) { int height = heights[stack.pop()]; int width = stack.isEmpty() ? i : i - stack.peek() - 1; maxArea = Math.max(maxArea, height * width); } stack.push(i); } return maxArea; }
public static void main(String[] args) { int[] heights = {2, 1, 5, 6, 2, 3}; System.out.println("Largest rectangle: " + largestRectangleArea(heights)); }}Largest rectangle: 10
What this code does
- Bars with heights 5 and 6 form a rectangle of height 5 and width 2.
- Area is 5 * 2 = 10.
- Appending dummy height 0 at index n flushes all remaining stack elements.
Brute force expands left and right from every bar: O(n) steps per bar, O(n²) in total (the first example). The stack finds both boundaries for all bars in O(n).
When a shorter bar arrives at index i, the taller bar on top of the stack has found its right boundary. Popping it fixes its height, and the new stack top is its left boundary, so the width is i - stack.peek() - 1 (or i if the stack is empty).
Trace on [2, 1, 5, 6, 2, 3]:
- Index 0 (height 2): push 0.
- Index 1 (height 1): 1 < 2, so pop 0; area 2 * 1 = 2; push 1.
- Indexes 2 and 3 (heights 5 and 6) increase, so push both.
- Index 4 (height 2): pop 3 (height 6), area 6 * 1 = 6. Still 2 < 5, so pop 2 (height 5), width 4 - 1 - 1 = 2, area 10.
- Push 4 and 5, then flush the stack at the end. The largest area is 10.
- Increasing stack: holds indices of bars in strictly increasing height order.
- Right boundary: index of current smaller bar that triggered the pop.
- Left boundary: index of previous smaller bar remaining on stack after the pop.
- Width formula:
i - stack.peek() - 1(oriif stack is empty).
Extending histogram logic to maximal rectangle in a 2D matrix
To find the largest rectangle of 1s in a binary matrix, treat each row as the base of a histogram and run the stack algorithm row by row.
Example 3 · Maximal Rectangle in Binary Matrix
import java.util.ArrayDeque;import java.util.Deque;
public class MaximalRectangleMatrixDemo { private static int largestInRow(int[] heights) { int n = heights.length, max = 0; Deque<Integer> st = new ArrayDeque<>(); for (int i = 0; i <= n; i++) { int h = (i == n) ? 0 : heights[i]; while (!st.isEmpty() && h < heights[st.peek()]) { int height = heights[st.pop()]; int width = st.isEmpty() ? i : i - st.peek() - 1; max = Math.max(max, height * width); } st.push(i); } return max; }
public static int maximalRectangle(char[][] matrix) { if (matrix.length == 0) return 0; int cols = matrix[0].length; int[] heights = new int[cols]; int maxArea = 0;
for (char[] row : matrix) { for (int c = 0; c < cols; c++) { heights[c] = (row[c] == '1') ? heights[c] + 1 : 0; } maxArea = Math.max(maxArea, largestInRow(heights)); } return maxArea; }
public static void main(String[] args) { char[][] matrix = { {'1', '0', '1', '0', '0'}, {'1', '0', '1', '1', '1'}, {'1', '1', '1', '1', '1'}, {'1', '0', '0', '1', '0'} }; System.out.println("Maximal rectangle: " + maximalRectangle(matrix)); }}Maximal rectangle: 6
What this code does
- Row 2 creates histogram heights
[3, 1, 3, 2, 2]. - Row 2 contains a 3x2 rectangle of 1s with area 6.
- Total time is linear in matrix cell count O(R * C).
Brute force checks every sub-rectangle in O(R³ * C³) time. The histogram reduction needs only O(R * C).
Keep an array heights with one entry per column. For each row, add 1 where the cell is 1 and reset to 0 where it is 0, run the histogram method, and track the best area.
On a 3-row example, row 0 gives heights [1, 0, 1] (best area 1), row 1 gives [2, 1, 2] (best area 3) and row 2 gives [3, 2, 0], where the bars 3 and 2 form a 2 x 2 rectangle of area 4.
- Dynamic height tracking: reset to 0 on
'0', increment on'1'. - Row-by-row histogram: run monotonic stack on updated heights array.
- Total time: O(R * C), dramatically faster than brute force O(R³ * C³).
Trapping rain water with a monotonic stack
Rain water gets trapped in dips bounded by taller left and right bars. Brute force scans left and right from each bar for maximum heights in O(n²) time. A decreasing stack computes trapped water horizontally layer by layer in O(n) time.
Example 4 · Trapping Rain Water Using a Stack
import java.util.ArrayDeque;import java.util.Deque;
public class TrappingRainWaterStackDemo { public static int trap(int[] height) { int n = height.length; Deque<Integer> stack = new ArrayDeque<>(); int water = 0;
for (int i = 0; i < n; i++) { while (!stack.isEmpty() && height[i] > height[stack.peek()]) { int mid = stack.pop(); if (stack.isEmpty()) break; int left = stack.peek(); int boundedHeight = Math.min(height[left], height[i]) - height[mid]; int width = i - left - 1; water += boundedHeight * width; } stack.push(i); } return water; }
public static void main(String[] args) { int[] heights = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; System.out.println("Trapped water: " + trap(heights)); }}Trapped water: 6
What this code does
- Basins between taller bars accumulate water horizontally.
- A total of 6 units of water are trapped.
- The stack algorithm runs in O(n) time and O(n) space.
The stack stores indices of bars waiting for a taller right boundary.
When an incoming bar is taller than the stack top, a water basin is formed.
Pop the basin floor as mid; the new stack top is the left wall, and current index is the right wall.
Bounded height is min(height[left], height[right]) - height[mid], and width is right - left - 1. Consider heights [3, 0, 2].
Index 0 (height 3): push 0.
Index 1 (height 0): 0 < 3, so push 1.
Index 2 (height 2): 2 > 0, so pop 1 as floor mid.
Left wall is index 0 (height 3), right wall is index 2 (height 2).
Bounded height is min(3, 2) - 0 = 2, and width is 2 - 0 - 1 = 1.
Trapped water is 2 * 1 = 2 units.
Remember:
- Decreasing stack: stores indices waiting for a taller right boundary.
- Basin bottom: popped index
midforms the base of trapped water. - Bounded height:
min(heights[left], heights[right]) - heights[mid]. - Trapped water:
boundedHeight * (right - left - 1).
Next step
Check your understanding
10 quick questions