Challenge - 5 Problems
Stack Rain Water Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Trapping Rain Water Calculation
What is the output of the following C code that calculates trapped rain water using a stack?
DSA C
int trap(int* height, int heightSize) { int stack[heightSize]; int top = -1; int water = 0; int i = 0; while (i < heightSize) { while (top != -1 && height[i] > height[stack[top]]) { int topIndex = stack[top--]; if (top == -1) break; int distance = i - stack[top] - 1; int bounded_height = (height[i] < height[stack[top]] ? height[i] : height[stack[top]]) - height[topIndex]; water += distance * bounded_height; } stack[++top] = i++; } return water; } int main() { int height[] = {0,1,0,2,1,0,1,3,2,1,2,1}; int size = sizeof(height)/sizeof(height[0]); int result = trap(height, size); printf("%d\n", result); return 0; }
Attempts:
2 left
💡 Hint
Trace the stack operations and calculate trapped water between bars.
✗ Incorrect
The code uses a stack to find boundaries and calculates trapped water between them. For the given input, the total trapped water units are 6.
❓ Predict Output
intermediate2:00remaining
Result of Trapping Rain Water for Different Input
What is the output of the trapping rain water function for this input array?
DSA C
int height[] = {4,2,0,3,2,5}; int size = sizeof(height)/sizeof(height[0]); int result = trap(height, size); printf("%d\n", result);
Attempts:
2 left
💡 Hint
Calculate trapped water between bars using stack logic.
✗ Incorrect
The trapped water units for the input {4,2,0,3,2,5} is 9.
🔧 Debug
advanced2:00remaining
Identify the Error in Stack Implementation
What error will occur if the stack array is declared as int stack[heightSize-1] instead of int stack[heightSize] in the trapping rain water code?
DSA C
int stack[heightSize-1]; int top = -1; // rest of the code unchanged
Attempts:
2 left
💡 Hint
Consider the maximum number of elements pushed onto the stack.
✗ Incorrect
The stack size must be at least heightSize to hold all indices. Using heightSize-1 causes buffer overflow when pushing the last index.
🧠 Conceptual
advanced2:00remaining
Why Use Stack for Trapping Rain Water?
Why is a stack used in the trapping rain water problem instead of a simple two-pointer approach?
Attempts:
2 left
💡 Hint
Think about how the stack stores indices of bars and helps find boundaries.
✗ Incorrect
Stack stores indices of bars in increasing height order to find boundaries and calculate trapped water efficiently in one pass.
🚀 Application
expert3:00remaining
Maximum Water Trapped with Modified Input
Given the input array {5,2,1,2,1,5}, what is the maximum amount of water trapped calculated by the stack method?
Attempts:
2 left
💡 Hint
Visualize the bars and calculate trapped water between boundaries.
✗ Incorrect
The trapped water units for {5,2,1,2,1,5} is 14 units.
