Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Two pointers

Two walls holding the most water

Medium · Target 15 minutes · Two pointers· Type asked at

Container with most water in one pass

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.

Where people lose marks

  • Moving the taller wall. The width shrinks and the height is still limited by the shorter wall, so it can only get worse; you may skip the optimum.
  • Measuring the height as the taller wall, or as the sum. Water spills over the shorter one.
  • Measuring the width as hi − lo + 1. The walls have no thickness here; the distance between positions 0 and 1 is 1.
  • Worrying about ties. When both walls are equal, moving either is safe, since neither can be in a better pair with anything between them.
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.