Data Structures & AlgorithmsVery hardAmazon/Microsoft SDE pattern

Elevation map [2, 2, 5, 0, 2, 0, 3, 1, 1, 1] (bar width 1). Using the two-pointer / prefix-max approach for trapping rain water, how much water is trapped in total?

  1. A. 4
  2. B. 27
  3. C. 7
  4. D. 17

Correct answer: C. 7

Water trapped above position i equals min(max to its left, max to its right) − height[i], summed over all positions (never negative). Computing this gives 7 units. Using only the running left-max (ignoring the right side), as in 27, overcounts positions where the right boundary is actually the limiting (shorter) wall.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic