Bird
0
0
DSA Cprogramming~10 mins

Trapping Rain Water Using Stack in DSA C - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare the stack pointer for indices.

DSA C
int stack[100];
int top = [1];
Drag options to blanks, or click blank then click option'
A0
B100
C-1
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing top to 0 causes off-by-one errors.
Using 100 as top index causes out-of-bounds.
2fill in blank
medium

Complete the code to push an index onto the stack.

DSA C
stack[++top] = [1];
Drag options to blanks, or click blank then click option'
Ai
Bstack[top]
Ctop
Dheight[i]
Attempts:
3 left
💡 Hint
Common Mistakes
Pushing height[i] instead of index causes logic errors.
Pushing top or stack[top] causes wrong stack content.
3fill in blank
hard

Fix the error in calculating the distance between bars.

DSA C
distance = i - stack[[1]] - 1;
Drag options to blanks, or click blank then click option'
Atop
Btop + 1
Ctop - 1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using top - 1 calculates overly wide distance.
Using top + 1 causes out-of-bounds access.
4fill in blank
hard

Fill both blanks to calculate bounded height and update trapped water.

DSA C
bounded_height = (height[i] < height[stack[top]]) ? height[i] - height[stack[[1]]] : height[stack[top]] - height[stack[[2]]];
water += distance * bounded_height;
Drag options to blanks, or click blank then click option'
Atop - 1
Btop
Ctop + 1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using top subtracts left height (zero water).
Using top - 1 subtracts wrong bar height.
5fill in blank
hard

Fill all three blanks to complete the main loop for trapping rain water.

DSA C
for (int i = 0; i < n; i++) {
    while (top != -1 && height[i] > height[stack[top]]) {
        int top_index = stack[top--];
        if (top == -1) continue;
        int distance = i - stack[[1]] - 1;
        int bounded_height = (height[i] < height[stack[top]]) ? height[i] - height[stack[[2]]] : height[stack[top]] - height[stack[[3]]];
        water += distance * bounded_height;
    }
    stack[++top] = i;
}
Drag options to blanks, or click blank then click option'
Atop
Btop - 1
Ctop + 1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using top - 1 for distance causes wrong width.
Swapping indices in bounded_height causes wrong height calculation.