Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Hard Two Pointers High frequency Solution Available Practice Mode

Trapping Rain Water LeetCode Solution

Tags: #Array #Two Pointers #Stack #DP

Approach Summary

Track max height from left and right. Water at each position is min(maxLeft, maxRight) - height. Move the pointer with the smaller max.

Practice Mode

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Two Pointers Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Two Pointers pattern.

Framework: Two Pointers • Interview Prep: Tested at FAANG • Explore all Two Pointers problems & invariants →

How to Recognize This Pattern

  • Water trapped between bars
  • Classic two-pointer/DP hybrid

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)

Tags

Array Two Pointers Stack DP

Frequently Asked Questions

What is the optimal time and space complexity for Trapping Rain Water?
The optimal solution for Trapping Rain Water achieves O(n) runtime complexity and requires O(1) auxiliary space. Each bar is visited once by one of the two pointers — O(n) time. Only two running maxima and the pointers — O(1) space.
How do I identify that Trapping Rain Water requires the Two Pointers pattern?
In technical interviews, look for key problem signals: Water trapped between bars; Classic two-pointer/DP hybrid. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Two Pointers strategy.
What critical edge cases must be handled in Trapping Rain Water?
Essential edge cases to verify include: Monotonically increasing heights — no water at all; Flat profile with a dip — water fills the dip; Two tall towers sandwiching short bars — the classic full trap; Empty or single-element array — return 0. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Trapping Rain Water?
Trapping Rain Water is a Hard-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Amazon, Google, Facebook, Apple.
Buy me a coffee
Daily Practice
0/0