NeetCode 150 / Two Pointers
HardTwo PointersO(n)

Dry run

height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]Step 1 of 13
0
0l
1
1
0
2
2
3
1
4
0
5
1
6
3
7
2
8
1
9
2
10
1
11r
trapped
0

Two pointers at the ends. Water above each bar is capped by the taller wall on whichever side is currently shorter.

Pythontime O(n) · space O(1)
1def trap(height):
2 l, r = 0, len(height) - 1
3 leftMax = rightMax = water = 0
4 while l < r:
5 if height[l] < height[r]:
6 leftMax = max(leftMax, height[l])
7 water += leftMax - height[l]
8 l += 1
9 else:
10 rightMax = max(rightMax, height[r])
11 water += rightMax - height[r]
12 r -= 1
13 return water
Variables
l0
r11
leftMax0
rightMax0
water0

Problem

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Examples

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]Output: 6
Input: height = [4,2,0,3,2,5]Output: 9

Constraints

  • n == height.length
  • 1 ≤ n ≤ 2 × 10⁴
  • 0 ≤ height[i] ≤ 10⁵

Intuition

The water sitting above any bar is capped by the shorter of the tallest wall to its left and the tallest wall to its right. Rather than computing both walls for every index up front, walk two pointers inward: whichever side currently has the shorter bar is the one whose water level is already fully determined by its running max, so settle that side and advance it — the other side's true max can only help, never hurt, the bound already in hand.

Brute force → Optimal

Brute force

For each index, scan left for the tallest bar and scan right for the tallest bar, then add min(leftMax, rightMax) − height[i].

Time O(n²)Space O(1)
Optimal

Two pointers from both ends, each tracking its own running max. Always advance the side with the smaller current bar, since its water level is already decided.

Time O(n)Space O(1)

Complexity

Time O(n)Space O(1)

Edge cases

  • Strictly increasing or strictly decreasing heights: no water is ever trapped, the answer is 0.
  • A single bar or an empty map: there's nothing to trap between, the answer is 0.

Common mistakes

  • Precomputing two full leftMax/rightMax arrays when the two-pointer version needs only O(1) extra space.
  • Moving the pointer on the *taller* side instead of the shorter one, which breaks the guarantee that the moved side's water level is already final.

জটিলতা

O(n)
সময় — অ্যারেটা একবারই ঘুরি, ম্যাপে খোঁজা O(1)।
O(1)
জায়গা — সবচেয়ে খারাপ ক্ষেত্রে সব সংখ্যা ম্যাপে থাকে।
আগের সমস্যা← Container With Most Waterপরের সমস্যাBest Time to Buy and Sell Stock →