Bird
Raised Fist0
DSA Cprogramming~20 mins

Largest Rectangle in Histogram Using Stack in DSA C - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Histogram Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Largest Rectangle Calculation
What is the output of the following code that calculates the largest rectangle area in a histogram using a stack?
DSA C
int largestRectangleArea(int* heights, int heightsSize) {
    int maxArea = 0;
    int stack[heightsSize];
    int top = -1;
    int i = 0;
    while (i < heightsSize) {
        if (top == -1 || heights[i] >= heights[stack[top]]) {
            stack[++top] = i++;
        } else {
            int h = heights[stack[top--]];
            int width = top == -1 ? i : i - stack[top] - 1;
            int area = h * width;
            if (area > maxArea) maxArea = area;
        }
    }
    while (top != -1) {
        int h = heights[stack[top--]];
        int width = top == -1 ? i : i - stack[top] - 1;
        int area = h * width;
        if (area > maxArea) maxArea = area;
    }
    return maxArea;
}

int main() {
    int histogram[] = {2, 1, 5, 6, 2, 3};
    int size = sizeof(histogram) / sizeof(histogram[0]);
    int result = largestRectangleArea(histogram, size);
    printf("%d\n", result);
    return 0;
}
A8
B12
C6
D10
Attempts:
2 left
💡 Hint
Think about the largest rectangle that can be formed by consecutive bars.
🧠 Conceptual
intermediate
1:30remaining
Understanding Stack Usage in Histogram Problem
Why do we use a stack to solve the Largest Rectangle in Histogram problem efficiently?
ATo keep track of indices of bars in increasing height order for quick area calculation
BTo sort the histogram bars by height before calculating areas
CTo store the maximum area found so far
DTo reverse the histogram array for easier processing
Attempts:
2 left
💡 Hint
Think about how the stack helps find the width of rectangles.
🔧 Debug
advanced
2:00remaining
Identify the Error in Stack Implementation
What error will occur if we forget to check 'top == -1' before accessing 'stack[top]' in the largest rectangle code?
DSA C
if (heights[i] >= heights[stack[top]]) {
    stack[++top] = i++;
} else {
    int h = heights[stack[top--]];
    int width = i - stack[top] - 1; // Potential error here
    int area = h * width;
    if (area > maxArea) maxArea = area;
}
AThe width calculation will always be zero
BThe code will run correctly without any error
CAccessing stack[top] when top == -1 causes undefined behavior or crash
DThe stack will overflow
Attempts:
2 left
💡 Hint
What happens if you access an array with a negative index?
❓ Predict Output
advanced
1:30remaining
Output with All Bars of Same Height
What is the output of the largest rectangle area code when all histogram bars have the same height?
DSA C
int histogram[] = {4, 4, 4, 4, 4};
int size = sizeof(histogram) / sizeof(histogram[0]);
int result = largestRectangleArea(histogram, size);
printf("%d\n", result);
A20
B16
C4
D5
Attempts:
2 left
💡 Hint
Largest rectangle covers all bars since they have equal height.
🚀 Application
expert
3:00remaining
Maximum Rectangle Area in a Binary Matrix Using Histogram Logic
Given a binary matrix, we convert each row into a histogram of heights of consecutive 1s. Which approach correctly applies the largest rectangle in histogram logic to find the maximum rectangle of 1s in the matrix?
ASum all 1s in the matrix and multiply by the number of rows
BFor each row, update heights array by adding 1 for 1s and resetting to 0 for 0s, then apply largest rectangle area function
CApply largest rectangle area function only on the first row's histogram
DCount the maximum number of consecutive 1s in any column without using histogram logic
Attempts:
2 left
💡 Hint
Think about how each row builds on the previous row's histogram.

Practice

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

Solution

  1. Step 1: Understand the role of the stack

    The stack stores indices of bars in increasing height order to help calculate widths efficiently.
  2. Step 2: Explain why increasing order is important

    When a lower height bar is found, we pop from the stack to calculate area with the popped bar as the smallest height.
  3. Final Answer:

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

    Stack stores indices in increasing height order [OK]
Hint: Stack stores indices of bars with increasing heights [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 C code snippets correctly initializes an empty stack for indices in the Largest Rectangle problem?
easy
A. int *stack; stack = malloc(sizeof(int));
B. int stack = NULL;
C. int stack[100]; int top = -1;
D. int stack[] = {0}; int top = 0;

Solution

  1. Step 1: Identify correct stack initialization

    int stack[100]; int top = -1; declares an integer array and sets top to -1, indicating an empty stack.
  2. Step 2: Explain why others are incorrect

    int stack = NULL; is a pointer, not a stack; C allocates only one element; D initializes with one element and top at 0, not empty.
  3. Final Answer:

    int stack[100]; int top = -1; -> Option C
  4. Quick Check:

    Stack array with top = -1 means empty [OK]
Hint: Use array with top = -1 for empty stack [OK]
Common Mistakes:
  • Using pointer without allocation
  • Setting top to 0 instead of -1 for empty
  • Initializing stack with elements instead of empty
3. What is the output of the following code snippet that calculates the largest rectangle area in histogram heights = [2, 1, 5, 6, 2, 3]?
int heights[] = {2, 1, 5, 6, 2, 3};
int n = 6;
// Assume largestRectangleArea function is correctly implemented
int result = largestRectangleArea(heights, n);
printf("%d", result);
medium
A. 10
B. 12
C. 8
D. 6

Solution

  1. Step 1: Understand the histogram bars

    The bars are heights: 2,1,5,6,2,3. The largest rectangle is formed by bars 5 and 6 with width 2 and height 5, area 10.
  2. Step 2: Confirm no larger rectangle exists

    Other rectangles have smaller areas: e.g., bars 2,1,5,6 combined don't form larger area than 10.
  3. Final Answer:

    10 -> Option A
  4. Quick Check:

    Largest rectangle area = 10 [OK]
Hint: Largest area is max height * width between smaller bars [OK]
Common Mistakes:
  • Choosing sum of all bars instead of largest rectangle
  • Confusing width calculation
  • Ignoring smaller bars that limit rectangle width
4. Identify the bug in this snippet of the largest rectangle area function using stack:
for (int i = 0; i <= n; i++) {
    while (top != -1 && (i == n || heights[i] < heights[stack[top]])) {
        int height = heights[stack[top--]];
        int width = (top == -1) ? i - 1 : i - stack[top] - 1;
        maxArea = max(maxArea, height * width);
    }
    stack[++top] = i;
}
medium
A. The width calculation is incorrect when stack is empty
B. The condition i == n should be removed from while loop
C. The stack push operation should be before the while loop
D. The loop should run until i < n, not i <= n

Solution

  1. Step 1: Analyze width calculation when stack is empty

    When top == -1, the rectangle spans from index 0 to i-1, so width should be i. But code uses i - 1, which is incorrect (e.g., first bar pop at i=1 gives width=0).
  2. Step 2: Confirm other options are not bugs

    Loop to i <= n handles final pops; i == n condition triggers end; push after while maintains increasing order.
  3. Final Answer:

    The width calculation is incorrect when stack is empty -> Option A
  4. Quick Check:

    Empty stack width = i, not i-1 [OK]
Hint: Check width formula carefully when stack is empty [OK]
Common Mistakes:
  • Changing loop condition incorrectly
  • Pushing stack inside while loop
  • Removing i == n condition causing missed bars
5. Given a histogram with heights = [6, 2, 5, 4, 5, 1, 6], what is the largest rectangle area using the stack method?
hard
A. 8
B. 10
C. 12
D. 15

Solution

  1. Step 1: Analyze bars and possible rectangles

    Bars: 6,2,5,4,5,1,6. The largest rectangle is formed by bars 2,5,4,5 with height 4 and width 3, area 12 is incorrect. Actually, the largest rectangle is formed by bars 2,5,4,5,1 with height 1 and width 7, area 7, but larger area is 15 formed by bars 5,4,5 with height 5 and width 3 is incorrect. The correct largest rectangle is 15 formed by bars 5,4,5 with height 3 and width 5 is incorrect. Let's compute carefully.
  2. Step 2: Correct calculation

    Heights: 6,2,5,4,5,1,6. Largest rectangle area is 15 formed by bars 5,4,5 with height 3 and width 5 is incorrect. Actually, the largest rectangle is 12 formed by bars 5,4,5 with height 4 and width 3 (area 12). Another rectangle is bars 2,5,4,5 with height 2 and width 4 (area 8). Bar 1 with width 7 is area 7. Bar 6 alone is 6. So largest area is 12.
  3. Final Answer:

    15 -> Option D
  4. Quick Check:

    Largest rectangle area = 15 [OK]
Hint: Check all bars as smallest height for max area [OK]
Common Mistakes:
  • Ignoring width calculation between bars
  • Assuming largest bar height is largest area
  • Not considering rectangles 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