Approach 1: O(n) Space - Two Arrays (Easier to conceptualize)

Core Idea: Pre-compute the maximum heights on the left and right of every position, then calculate water trapped.

Steps:

  1. Create two arrays: max_left[] and max_right[], both of size n
  2. First pass (left to right): Fill max_left[i] = maximum height from index 0 to i
  3. Second pass (right to left): Fill max_right[i] = maximum height from index i to end
  4. Third pass: For each position, calculate water:

Why it works: You have complete information about what's on both sides of every position before calculating water.

Time: O(n) - three passes Space: O(n) - two arrays


Approach 2: O(1) Space - Two Pointers (Optimal but trickier)

Core Idea: Use two pointers moving from both ends, maintaining running maximums, and only calculate water on the side with the SMALLER maximum.

Key Insight: You don't need to know BOTH max_left and max_right for a position if you know one side's max is definitely smaller. The smaller side is the bottleneck (determines water level), so you can calculate water there immediately.

Steps:

  1. Initialize: left = 0, right = n-1, left_max = 0, right_max = 0, water = 0
  2. While left < right:

Why it works: