PythonStudio
Interview Problems

Trapping Rain Water

hard · two pointers

You are given a list `height` where height[i] is the height of a wall at position i. After it rains, water collects in the dips between walls. At any position, the water level is limited by the tallest wall to its left and the tallest wall to its right. Compute the total number of units of water trapped. Input: `height` (a list of non-negative integers). Output: the total units of trapped water. Example: height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] -> 6.

Starter code

def trap(height: list[int]) -> int:
    """Return how many units of rain water are trapped after raining."""
    pass

Enable JavaScript to edit this code and run the hidden tests in your browser. Each test has a five-second execution limit. Your drafts and solved progress stay in this browser.

Return to the Python compiler