An interactive visualization of how the two-pointer technique calculates water trapped between elevation bars. Watch left and right pointers converge while tracking maximum heights.
Two Pointers LeetCode 42 ↗ Hardn non-negative integers representing an elevation map where the width of each bar is 1,
compute how much water it can trap after raining.height = [0,1,0,2,1,0,1,3,2,1,2,1], the answer is 6 units of water trapped.fun trap(height: IntArray): Int { var left = 0; var right = height.size - 1 var leftMax = 0; var rightMax = 0 var water = 0 while (left < right) { if (height[left] < height[right]) { if (height[left] >= leftMax) leftMax = height[left] else water += leftMax - height[left] left++ } else { if (height[right] >= rightMax) rightMax = height[right] else water += rightMax - height[right] right-- } } return water}
The water above any position i is determined by the minimum of the maximum heights
to its left and right, minus its own height: water[i] = min(left_max, right_max) - height[i].
The two-pointer approach exploits the fact that we only need to know the smaller of the two maxima
at any time, which is always on the side of the shorter pointer.
left at index 0 and right at the last index. Set left_max = 0 and right_max = 0.height[left] < height[right], the left side is the bottleneck — process the left pointer.height[left] >= left_max, update left_max. Otherwise, water at this position is left_max - height[left]. Then advance left.height[right] >= right_max, update right_max. Otherwise, add right_max - height[right]. Then decrease right.left >= right, all positions have been processed.
Each pointer moves at most n steps total, so the algorithm processes the entire array in a single pass with constant extra space.
This is optimal — we must examine each element at least once.