LeetCode 42: Trapping Rain Water — Python Solution

Solve LeetCode 42: Trapping Rain Water in Python with a two pointers with bounded sides approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyHard
TopicArray / String
Reusable patterntwo pointers with bounded sides
ComplexityO(n) time and O(1) extra space

What the problem is testing

Move the side with the lower current maximum. That lower boundary already determines how much water can be trapped at its pointer.

Algorithm

  1. Move the side with the lower current maximum. That lower boundary already determines how much water can be trapped at its pointer.
  2. Maintain this invariant: Processed positions have their final water amount because their limiting boundary is known.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Solution:
    def trap(self, height):
        left, right = 0, len(height) - 1
        left_max = right_max = water = 0
        while left <= right:
            if left_max <= right_max:
                left_max = max(left_max, height[left])
                water += left_max - height[left]
                left += 1
            else:
                right_max = max(right_max, height[right])
                water += right_max - height[right]
                right -= 1
        return water

Why this is correct

The proof follows the maintained state: Processed positions have their final water amount because their limiting boundary is known. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(n) time and O(1) extra space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

Fewer than three bars trap nothing; equal-height walls are handled by either side.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 135. Candy · Next: 13. Roman to Integer