← Deloitte bank

Deloitte · Question 73

Largest Rectangle in Histogram

Javacode⏱ O(n)💾 O(n)
Service-based

Problem

Use a monotonic increasing stack of indices to compute the max area.

Approach

Each popped bar extends between smaller bars.

Time O(n)Space O(n)

How it works

  1. 1Push rising bars; a drop pops and measures.
  2. 2Width spans from the new top to i.

Sample input / output

Input:
heights = [2, 1, 5, 6, 2, 3]
Output:
10

Constraints

1 <= heights.length <= 10^5.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 2Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intlargestRectangleArea(int[]h)Stack<Integer> st = newStack<>()DEFINE n = h.length, max =0for (int i = 0; i <=n; i++)DEFINE cur = (i == n) ? 0 :h[i]while (!st.isEmpty()&& cur < h[st.peek()])DEFINE height = h[st.pop()]DEFINE width = st.isEmpty()? i : i - st.peek() - 1max = Math.max(max, height* width)st.push(i)RETURN maxDEFINE static voidmain(String[] args)System.out.println(largestRectangleArea(newint[]{2, 1, 5, 6, 2, 3}))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/16

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits