NeetCode #218LC-42HardTwo PointersNC 150NC 250
← Back to All Problems#218 · #42 · Trapping Rain Water(接雨水)
📌 Problem Statement & Constraints
Given
n non-negative integers representing an elevation map where each bar has width 1, compute how much water it can trap after raining. Constraints: 1 <= n <= 2 * 10^4, 0 <= height[i] <= 10^5.💡 Core Algorithmic Approaches
- The water above bar
iismin(max_left, max_right) - height[i], where the maxima excludeiitself. - The straightforward solution precomputes prefix maxima and suffix maxima, giving O(n) time and O(n) space.
- Two-pointer refinement: maintain
left_maxandright_maxwhile closing in from both ends. Whenleft_max < right_max, the water at the left pointer is fully determined byleft_max, so it can be settled immediately. - This reduces the extra space to O(1) while keeping O(n) time.
💻 Benchmark Python3 Implementation
class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
i, j = 0, len(height) - 1
left_max = right_max = 0
water = 0
while i < j:
left_max = max(left_max, height[i])
right_max = max(right_max, height[j])
if left_max < right_max:
# the left bar is the limiting side -> its water is final
water += left_max - height[i]
i += 1
else:
water += right_max - height[j]
j -= 1
return water
# Prefix/suffix maxima variant: O(n) space, easier to reason about
class Solution2:
def trap(self, height: List[int]) -> int:
n = len(height)
if n == 0:
return 0
left = [0] * n
right = [0] * n
left[0] = height[0]
for i in range(1, n):
left[i] = max(left[i - 1], height[i])
right[n - 1] = height[n - 1]
for i in range(n - 2, -1, -1):
right[i] = max(right[i + 1], height[i])
return sum(min(left[i], right[i]) - height[i] for i in range(n))⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass with two pointers, or two passes plus a sum for the prefix variant.
💾 Space Complexity
O(1) for the two-pointer version, O(n) for the prefix/suffix arrays.
⚠️ Interview Pitfalls & Follow-ups
- Including
height[i]in its own maxima: the water at a bar depends on the tallest bars strictly to either side, but takingmax(left_max, height[i])is actually fine because the resulting term isleft_max - height[i] >= 0. The subtle point is that you must update the maxima before adding the water, or negative contributions appear. - Adding water before updating the maxima: with
left_maxinitialised to 0, the first bar would contribute a negative amount. - Assuming the two-pointer choice is arbitrary: the correctness relies on settling the side with the smaller maximum, because the other side already guarantees at least that much water.
- Using
<=in the branch: ties can go either way, but exactly one branch must execute per iteration.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Two Pointers Problems
中文速览与面试要点
接雨水
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。约束:n == height.length;1 ≤ n ≤ 2 × 10^4;0 ≤ height[i] ≤ 10^5。
核心要点
- 核心公式 :位置 i 能接的雨水量 = min(左侧最高, 右侧最高) − height[i] (若为负则取 0)。
- 预处理左右最大值 :先从左往右求 left_max[i] 、从右往左求 right_max[i] ,再逐位置累加。时间 O(n)、空间 O(n)。
- 双指针优化到 O(1) 空间(推荐) :维护 left_max 与 right_max 两个变量。每次比较二者, 较小的一侧 可以立即确定其接水量——因为该侧的真实边界(另一侧的最大值)至少不小于当前另一侧的最大值。
- 为什么双指针是对的 :若 left_max < right_max ,则对位置 l 而言,右侧最高(≥ right_max)> left_max,因此 min(左, 右) = left_max 已确定,可以直接结算 l 并右移。
常见陷阱
- 忘记减去 height[i] :只累加 min(left_max, right_max) 会把柱子本身也算成水。
- 把「先移动指针再更新 max」的顺序搞反 :必须先移动指针,再用新位置的 height 更新 max,然后累加。顺序错误会导致重复计算或漏算。
- 双指针版本中先比较 height[l] 与 height[r] :应该比较的是 left_max 与 right_max (两侧的历史最大值),而不是当前柱子高度。
- 忘记 max(0, ...) :公式 min(left, right) − height[i] 在双指针写法中天然非负(因为 left_max 已包含 height[l]),但预处理版本中若顺序有误会得到负数,需注意。
- 误以为可以用单调栈之外的简单方法 :单调栈(按行计算)也是 O(n),但实现更复杂;双指针是本题最优的写法。
参考实现
class Solution:
def trap(self, height: list[int]) -> int:
if not height:
return 0
l, r = 0, len(height) - 1
left_max = height[l]
right_max = height[r]
water = 0
while l < r:
if left_max < right_max:
l += 1
left_max = max(left_max, height[l])
water += left_max - height[l] # 此时左侧边界已确定
else:
r -= 1
right_max = max(right_max, height[r])
water += right_max - height[r]
return water
# 预处理数组版本(更直观,空间 O(n)):
# n = len(height)
# left = [0]*n; right = [0]*n
# left[0] = height[0]
# for i in range(1, n): left[i] = max(left[i-1], height[i])
# right[n-1] = height[n-1]
# for i in range(n-2, -1, -1): right[i] = max(right[i+1], height[i])
# return sum(min(left[i], right[i]) - height[i] for i in range(n))