Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Two pointers

Two walls holding the most water

Medium · Target 15 minutes · Two pointers · Type asked atBloombergAmazonGoldman Sachs

An array heights gives the heights of vertical walls standing at positions 0, 1, …, n − 1. Choose two walls; together with the ground they hold water up to the height of the shorter one. Return the largest amount of water two walls can hold, measured as min(heights[i], heights[j]) × (j − i).

Examples

InputOutputWhy
heights = [1, 8, 6, 2, 5, 4, 8, 3, 7]49Walls 1 and 8 (heights 8 and 7): 7 × 7.
heights = [1, 1]1The only pair.
heights = [4, 3, 2, 1, 4]16The two outer walls, both 4, are 4 apart.

Constraints

  • 2 ≤ n ≤ 10⁵
  • 0 ≤ heights[i] ≤ 10⁴

Hints

Hint 1

Start with the widest pair, the two ends. Every other pair is narrower, so it only wins if it is taller.

Hint 2

Compare the two end walls. Could the shorter one be part of a better pair with any wall between them?

Hint 3

No: paired with anything nearer, the width shrinks and the height is still capped by that shorter wall. Discard it and move that pointer inward.

Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.