Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the stack for indices.
DSA Go
stack := make([]int, 0) for i := 0; i < len(height); i++ { for len(stack) > 0 && height[i] > height[[1]] { top := stack[len(stack)-1] stack = stack[:len(stack)-1] // calculation here } stack = append(stack, i) }
Attempts:
3 left
💡 Hint
Common Mistakes
Using i instead of the top index of the stack.
Comparing with height[i] instead of height at stack top.
✗ Incorrect
We compare the current height with the height at the top index of the stack, which is stack[len(stack)-1].
2fill in blank
mediumComplete the code to calculate the distance between current index and new stack top.
DSA Go
distance := i - stack[len(stack)-1] - [1]
Attempts:
3 left
💡 Hint
Common Mistakes
Not subtracting 1, causing off-by-one error.
Using 0 or negative numbers incorrectly.
✗ Incorrect
Distance is the gap between current index and the new top of stack minus 1.
3fill in blank
hardFix the error in calculating bounded height for trapped water.
DSA Go
boundedHeight := min(height[i], height[stack[len(stack)-1]]) - height[[1]]
Attempts:
3 left
💡 Hint
Common Mistakes
Using i or stack top instead of the popped top index.
Subtracting wrong heights causing negative or wrong values.
✗ Incorrect
The bounded height is the difference between the smaller boundary height and the height at the popped top index.
4fill in blank
hardFill both blanks to correctly update the total trapped water.
DSA Go
water += [1] * [2]
Attempts:
3 left
💡 Hint
Common Mistakes
Multiplying wrong variables like height[i] or top.
Adding instead of multiplying.
✗ Incorrect
Total trapped water is the area: width (distance) times height (boundedHeight).
5fill in blank
hardFill all three blanks to complete the min function and the loop condition.
DSA Go
func min(a, b int) int { if a [1] b { return a } return b } for i := 0; i < len(height) && height[i] [2] height[stack[len(stack)-1]]; i++ { top := stack[len(stack)-1] stack = stack[:len(stack)-1] boundedHeight := min(height[i], height[stack[len(stack)-1]]) - height[top] distance := i - stack[len(stack)-1] - 1 water += distance * boundedHeight }
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong comparison operators causing logic errors.
Confusing '<' and '>' in min function and loop condition.
✗ Incorrect
The min function returns the smaller value using '<'. The loop continues while current height is greater than the height at stack top using '>'.
