Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing top to 0 causes off-by-one errors.
Using 100 as top index causes out-of-bounds.
✗ Incorrect
The stack top is initialized to -1 to indicate an empty stack.
2fill in blank
mediumComplete the code to push an index onto the stack.
DSA C
stack[++top] = [1]; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Pushing height[i] instead of index causes logic errors.
Pushing top or stack[top] causes wrong stack content.
✗ Incorrect
We push the current index i onto the stack, not the height value.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using top - 1 calculates overly wide distance.
Using top + 1 causes out-of-bounds access.
✗ Incorrect
Distance is between current index i and stack[top] (left bounding bar), so top is correct.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using top subtracts left height (zero water).
Using top - 1 subtracts wrong bar height.
✗ Incorrect
bounded_height is min(height[i], height[stack[top]]) minus height[stack[top + 1]] (popped bar index).
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using top - 1 for distance causes wrong width.
Swapping indices in bounded_height causes wrong height calculation.
✗ Incorrect
Distance uses top (left index). bounded_height uses top + 1 (popped index) correctly.
