← L&T Mindtree bank

L&T Mindtree · Question 26

Largest Rectangle in Histogram

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

Problem

You are given heights of bars in histogram. Find the largest rectangle area.

Approach

Monotonic stack with a sentinel; each popped bar bounds its max width.

Time O(n)Space O(n)

How it works

  1. 1Push rising bars; a drop pops and measures.
  2. 2Sentinel zero flushes the stack.

Sample input / output

Input:
heights = [2, 4]
Output:
4

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[]heights)Stack<Integer> st = newStack<>()DEFINE maxArea = 0, n =heights.lengthfor (int i = 0; i <=n; i++)DEFINE h = (i == n) ? 0 :heights[i]while (!st.isEmpty()&& h <heights[st.peek()])DEFINE height =heights[st.pop()]DEFINE width = st.isEmpty()? i : i - st.peek() - 1maxArea = Math.max(maxArea,height * width)st.push(i)RETURN maxAreaDEFINE static voidmain(String[] args)System.out.println(largestRectangleArea(newint[]{2, 4}))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