GOAT EngineerPreparing your learning space…

arrays · two pointers

The widest reservoir

Two walls hold water between them. Checking every pair is O(n²). Moving inward from both ends finds the same answer in one pass.

Step by step

  1. Nine walls. Which two trap the most water?

    Every pair is O(n²). It is correct, it is the first thing everyone writes, and it is not the answer anyone is looking for. The one-pass version turns on a single observation.

  2. The shorter wall caps it. The gap sets the width.

    Pick any two walls. The water they trap is the shorter wall times the gap between them. Your job is the biggest such rectangle.

  3. Start at the outside: min(1, 7) × 8 = 8

    The widest pair, and a poor one. The left wall is only 1 tall. So the water is 1 deep, however far the other wall stands.

  4. Which wall would you move?

    Only one of the two can be right, and the reason is the whole algorithm. Worth a moment before reading on.

  5. The shorter wall is the one that limits us

    Widening is impossible. The only hope is a taller limiting wall, and moving the TALLER one cannot give you that. So move the shorter.

  6. min(8, 7) × 7 = 49, and that is the record

    One step inward and the limit jumps from 1 to 7. Losing one unit of width bought six units of depth, which is exactly the trade the rule is chasing.

  7. Now the right wall is shorter, so it moves

    The rule does not care which side it is. Whichever wall limits the depth is the one with something to gain by moving.

  8. min(8, 8) × 5 = 40, still short of 49

    Two tall walls, but they have drifted too close together. Depth and width trade against each other the whole way in, and the best pair is rarely at either extreme.

  9. Can anything still beat 49?

    The pointers have not met yet, so the search is not over. But the answer is already decided, and the reason is the same rule.

  10. The span keeps narrowing and nothing beats it

    Every remaining pair is narrower than the record. Beating it would need a wall taller than 8. There is not one.

  11. The pointers meet, and 49 stands

    One pass, two integers of memory, and every pair that could have won was considered without ever being measured. That is what the rule buys.

Why moving the taller wall is always wrong

One step needs an argument, and it is short. Suppose the left wall is the shorter one. Every pair that keeps it has depth capped at that same short height, and a width no bigger than the one you have now.

The code

python

def widest(h):
    l, r = 0, len(h) - 1
    best = 0
    while l < r:
        area = min(h[l], h[r]) * (r - l)
        best = max(best, area)
        if h[l] < h[r]:
            l += 1
        else:
            r -= 1
    return best

Where it goes wrong

When the two walls are equal, either may move. Both choices are safe, for the same reason: whichever one stays behind still caps the depth.

All snippets