HARD NC#14 Two Pointers

42. Trapping Rain Water

📖 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.

🧠 Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • •Array methods (`push`, `pop`, `shift`, `slice`)
  • •Object/Map/Set usage patterns
  • •Function parameter and return typing
  • •In-place array updates
  • •Sorted array traversal
  • •Boundary condition checks

Logical Thinking Concepts

  • •Define invariants before coding
  • •Check edge cases first (`[]`, single element, duplicates)
  • •Estimate time/space before implementation
  • •Apply Two Pointers reasoning pattern

💡 Approach

  • → Water at index i = min(leftMax, rightMax) - height[i]
  • → Use two pointers from both ends
  • → Track max height seen from left and right
  • → Always move pointer with smaller max height
  • → Time: O(n), Space: O(1)

🛠️ Hints & Pitfalls

Hints

  • •Water at index i = min(leftMax, rightMax) - height[i]
  • •Use two pointers from both ends
  • •Track max height seen from left and right

Common Pitfalls

  • •Always move pointer with smaller max height
  • •Time: O(n), Space: O(1)

🧪 Test Cases

Hidden tests on submit: 2

Test Case 1
Not run
Input:
trap([0,1,0,2,1,0,1,3,2,1,2,1]);
Expected:
6
Test Case 2
Not run
Input:
trap([4,2,0,3,2,5]);
Expected:
9
Test Case 3
Not run
Input:
trap([0,0,0]);
Expected:
0

📝 Code Editor

📚 Reference Solution

▼
⌘K Search ⌘↩ Run ⌘S Submit