Data Structures19 sections · 729 units
Open in Course

Trapping Water - Implementation

Complete solution

Here's the stack solution:

function trap(height)
    stack := empty stack  // stores indices
    water := 0

    for i from 0 to length of height - 1
        while stack is not empty and height[i] > height[top of stack]
            mid := pop from stack
            if stack is empty
                break  // no left boundary
            left := top of stack
            width := i - left - 1
            h := min(height[i], height[left]) - height[mid]
            water := water + width × h
        push i onto stack

    return water

Time: O(n)O(n). Space: O(n)O(n).