Data Structures & AlgorithmsHardProduct Company SDE · ICPC regional

Problem: Water is poured into the cells of a 1-dimensional array of heights [0,1,0,2,1,0,1,3,2,1,2,1]; each cell holds water up to min(maximum height to its left, maximum height to its right) minus its own height if positive. What is the total units of trapped water?

  1. A. 6
  2. B. 22
  3. C. 11
  4. D. 5

Correct answer: A. 6

With prefix and suffix maxima (or two pointers), each cell holds min(leftMax, rightMax) − height, totalling 6. Using max instead of min gives 22, using only the left maximum gives 11, and counting the cells that hold water gives 5.

More Coding Interview Problems questions

Exams that ask this topic