Bird
Raised Fist0
DSA Typescriptprogramming~10 mins

Largest Rectangle in Histogram Using Stack in DSA Typescript - Execution Trace

Choose your learning style10 modes available
Concept Flow - Largest Rectangle in Histogram Using Stack
Start with empty stack
↓
Iterate over bars
↓
While current bar < top of stack bar
↓
Pop from stack and calculate area
↓
Update max area if needed
↓
Push current bar index to stack
↓
Repeat until all bars processed
↓
Pop remaining bars and calculate area
↓
Return max area
We scan bars left to right, using a stack to keep indexes of bars in ascending height order. When a lower bar appears, we pop taller bars to calculate areas, updating max area.
Execution Sample
DSA Typescript
function largestRectangleArea(heights: number[]): number {
  const stack: number[] = [];
  let maxArea = 0;
  for (let i = 0; i <= heights.length; i++) {
    while (stack.length && (i === heights.length || heights[i] < heights[stack[stack.length - 1]])) {
      const height = heights[stack.pop()!];
      const width = stack.length ? i - stack[stack.length - 1] - 1 : i;
      maxArea = Math.max(maxArea, height * width);
    }
    if (i < heights.length) {
      stack.push(i);
    }
  }
  return maxArea;
}

// Example: heights = [2,1,5,6,2,3] returns 10
Calculates the largest rectangle area in a histogram by using a stack to track bars and computing areas when a smaller bar is found.
Execution Table
StepOperationCurrent Index (i)Stack Content (indexes)Height at Top of StackActionMax AreaVisual State
1Start0[]N/APush 00[2]
2Next bar1[0]2Pop 0, Calculate area: height=2, width=12[]
3After pop1[]N/APush 12[1]
4Next bar2[1]1Push 22[1,5]
5Next bar3[1,2]5Push 32[1,5,6]
6Next bar4[1,2,3]6Pop 3, Calculate area: height=6, width=16[1,5]
7After pop4[1,2]5Pop 2, Calculate area: height=5, width=210[1]
8After pop4[1]1Push 410[1,2]
9Next bar5[1,4]2Push 510[1,2,3]
10End of array6[1,4,5]3Pop 5, Calculate area: height=3, width=110[1,2]
11After pop6[1,4]2Pop 4, Calculate area: height=2, width=410[1]
12After pop6[1]1Pop 1, Calculate area: height=1, width=610[]
13End6[]N/ADone10Final max area = 10
💡 All bars processed and stack emptied, max area found is 10
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5After Step 6After Step 7After Step 8After Step 9After Step 10After Step 11After Step 12Final
i00112344456666
stack[][0][][1][1,2][1,2,3][1,2][1][1,4][1,4,5][1,4][1][][]
maxArea002222610101010101010
Key Moments - 3 Insights
Why do we pop from the stack when the current bar is lower than the top of the stack?
Because the current lower bar means the previous taller bars can't extend further right. We calculate area for those popped bars using their height and width determined by current index and stack top (see steps 2,6,7,10,11,12 in execution_table).
Why do we push the current index after popping bars?
After popping taller bars, we push the current index to mark the start of a new potential rectangle with this lower height (see steps 3,8). This keeps stack in ascending order of heights.
Why do we run the loop until i <= heights.length instead of i < heights.length?
We run one extra iteration (i == heights.length) to pop and calculate areas for all remaining bars in the stack, ensuring no bars are left unprocessed (see steps 10,11,12 and 13).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 7, what is the maxArea after popping index 2?
A2
B10
C6
D0
💡 Hint
Check the 'Max Area' column at step 7 in execution_table
At which step does the maxArea first become 10?
AStep 6
BStep 8
CStep 7
DStep 12
💡 Hint
Look at the 'Max Area' column in execution_table and find when it updates to 10
At step 4 (i=2), why was there no pop from the stack before pushing 2?
Aheights[2] >= heights[1]
Bheights[2] < heights[1]
CStack was empty
Di was at end of array
💡 Hint
heights = [2,1,5,6,2,3], heights[2]=5 > heights[1]=1 (check step 4 stack top)
Concept Snapshot
Largest Rectangle in Histogram Using Stack
- Use a stack to store indexes of bars in ascending height
- Iterate bars, pop stack when current bar is lower
- Calculate area with popped bar height and width
- Update max area during pops
- After iteration, pop remaining bars
- Return max area found
Full Transcript
This visualization shows how to find the largest rectangle in a histogram using a stack. We keep indexes of bars in ascending height order. When a lower bar appears, we pop taller bars from the stack and calculate the area for each popped bar using its height and the width determined by the current index and the new top of the stack. We update the maximum area found so far during these calculations. After processing all bars, we pop any remaining bars to calculate their areas. The largest area found is returned. The execution table traces each step, showing stack content, current index, actions, and max area updates. The variable tracker shows how the index, stack, and max area change over time. Key moments clarify why we pop bars and why we do an extra iteration. The quiz tests understanding of these steps and stack behavior.

Practice

(1/5)
1. What is the main purpose of using a stack in the Largest Rectangle in Histogram problem?
easy
A. To reverse the order of histogram bars
B. To keep track of bars' indices with increasing heights
C. To store the maximum area found so far
D. To sort the histogram bars by height

Solution

  1. Step 1: Understand the stack's role

    The stack stores indices of bars in increasing height order to find boundaries for rectangles.
  2. Step 2: Why increasing heights?

    This helps identify when a bar is lower than the previous, signaling to calculate area for taller bars.
  3. Final Answer:

    To keep track of bars' indices with increasing heights -> Option B
  4. Quick Check:

    Stack tracks increasing bars = To keep track of bars' indices with increasing heights [OK]
Hint: Stack holds indices of increasing bars to find rectangle widths [OK]
Common Mistakes:
  • Thinking stack sorts bars by height
  • Using stack to store areas instead of indices
  • Ignoring the order of bars in the stack
2. Which of the following TypeScript code snippets correctly initializes an empty stack for indices in the Largest Rectangle problem?
easy
A. const stack = new Stack<number>();
B. const stack: string[] = [];
C. const stack: number[] = [];
D. const stack = []; stack.push('index');

Solution

  1. Step 1: Identify correct stack type

    We need a stack of numbers (indices), so number[] is correct.
  2. Step 2: Check other options

    const stack: string[] = []; uses string[], wrong type. const stack = new Stack<number>(); uses a Stack class which is not standard in TypeScript. const stack = []; stack.push('index'); pushes a string 'index', wrong type.
  3. Final Answer:

    const stack: number[] = []; -> Option C
  4. Quick Check:

    Stack of numbers = const stack: number[] = []; [OK]
Hint: Use number[] for stack of indices in TypeScript [OK]
Common Mistakes:
  • Using string[] instead of number[]
  • Assuming Stack class exists by default
  • Pushing wrong data types into stack
3. What is the output of the following TypeScript code snippet for histogram heights [2, 1, 5, 6, 2, 3]?
function largestRectangleArea(heights: number[]): number {
  const stack: number[] = [];
  let maxArea = 0;
  heights.push(0);
  for (let i = 0; i < heights.length; i++) {
    while (stack.length && heights[i] < heights[stack[stack.length - 1]]) {
      const height = heights[stack.pop()!];
      const width = stack.length ? i - stack[stack.length - 1] - 1 : i;
      maxArea = Math.max(maxArea, height * width);
    }
    stack.push(i);
  }
  return maxArea;
}

console.log(largestRectangleArea([2, 1, 5, 6, 2, 3]));
medium
A. 10
B. 12
C. 8
D. 6

Solution

  1. Step 1: Add sentinel and iterate

    Heights become [2,1,5,6,2,3,0]. We use stack to track indices of increasing bars.
  2. Step 2: Calculate max area during pops

    Pop bars when current height is less, calculate area: max area found is 10 (from bars 5 and 6 with width 2).
  3. Final Answer:

    10 -> Option A
  4. Quick Check:

    Max rectangle area = 10 [OK]
Hint: Add 0 height at end to flush stack and find max area [OK]
Common Mistakes:
  • Not adding sentinel 0 at end
  • Wrong width calculation after popping
  • Ignoring last bars in stack
4. Identify the bug in this TypeScript code snippet for Largest Rectangle in Histogram:
function largestRectangleArea(heights: number[]): number {
  const stack: number[] = [];
  let maxArea = 0;
  for (let i = 0; i <= heights.length; i++) {
    while (stack.length && heights[i] < heights[stack[stack.length - 1]]) {
      const height = heights[stack.pop()!];
      const width = stack.length ? i - stack[stack.length - 1] - 1 : i;
      maxArea = Math.max(maxArea, height * width);
    }
    stack.push(i);
  }
  return maxArea;
}
medium
A. maxArea is not updated inside the loop
B. Stack is not initialized properly
C. Width calculation is incorrect
D. Loop goes out of bounds accessing heights[i] when i == heights.length

Solution

  1. Step 1: Check loop boundary

    The loop runs i from 0 to heights.length inclusive, so heights[i] is accessed when i == heights.length, causing out-of-bounds error.
  2. Step 2: Fix by adding sentinel or changing loop

    Adding a 0 height at end or changing loop to i < heights.length fixes this.
  3. Final Answer:

    Loop goes out of bounds accessing heights[i] when i == heights.length -> Option D
  4. Quick Check:

    Out-of-bounds access = Loop goes out of bounds accessing heights[i] when i == heights.length [OK]
Hint: Avoid accessing heights[i] when i equals length without sentinel [OK]
Common Mistakes:
  • Ignoring loop boundary causing runtime error
  • Assuming stack initialization is wrong
  • Misreading width calculation
5. Given a histogram with heights [6, 2, 5, 4, 5, 1, 6], what is the largest rectangle area using the stack approach? Explain why the rectangle with area 12 is the largest.
hard
A. 12
B. 10
C. 15
D. 8

Solution

  1. Step 1: Use stack to find max area

    Push indices while heights increase. When a lower bar appears, pop and calculate area. For this histogram, max area is 12 from bars at indices 2,3,4 (heights 5,4,5) width 3.
  2. Step 2: Why area 12 is largest

    The rectangle covers bars with heights >=4 over width 3, area = 4*3=12. No other rectangle covers more area.
  3. Final Answer:

    12 -> Option A
  4. Quick Check:

    Max rectangle area = 12 [OK]
Hint: Pop stack on lower bar, calculate area with width between indices [OK]
Common Mistakes:
  • Calculating area only for single bars
  • Ignoring width when popping multiple bars
  • Missing the largest rectangle spanning multiple bars
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard