Trapping Rain Water Two Pointers
Walk two pointers inward tracking the tallest wall on each side; water above a column is bounded by the shorter of the two maxima.
Code
package main
import "fmt"
// trappingRainWater: two pointers walk inward tracking the tallest wall on
// each side; the water above a column is bounded by the shorter of the two
func trappingRainWater(height []int) int {
left, right := 0, len(height)-1
leftMax, rightMax := 0, 0
total := 0
for left < right {
if height[left] < height[right] {
if height[left] >= leftMax {
leftMax = height[left]
} else {
total += leftMax - height[left]
}
left++
continue
}
if height[right] >= rightMax {
rightMax = height[right]
} else {
total += rightMax - height[right]
}
right--
}
return total
}
func main() {
fmt.Println(trappingRainWater([]int{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}))
fmt.Println(trappingRainWater([]int{4, 2, 0, 3, 2, 5}))
fmt.Println(trappingRainWater([]int{3, 0, 3}))
}Execution shape
Read it this way: the functions trappingRainWater and main, doing all the work.
A single loop drives the file — for left < right.
What to watch for
- The runtime alone is required — nothing to fetch, nothing to install.
Applying it
The entry-point signature is func trappingRainWater(height []int) int
Launch the file; main takes over and steps through trappingRainWater.
Statements that matter
func main() {
fmt.Println(trappingRainWater([]int{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}))
fmt.Println(trappingRainWater([]int{4, 2, 0, 3, 2, 5}))
fmt.Println(trappingRainWater([]int{3, 0, 3}))
}
total += rightMax - height[right]
total += leftMax - height[left]
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Trapping Rain Water Two Pointers?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.