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.

GoData Integrity

Code

gosnippet
35 lines
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

FAQ

How do you run Trapping Rain Water Two Pointers?
The runtime alone is enough: execute the file as a complete program.