Data Structures & AlgorithmsHardTCS CodeVita · Microsoft SDE OA

Trapping rain water: heights h = [4, 2, 0, 3, 2, 5, 1, 0, 2]. Compute the total water trapped between the bars.

Trapping rain water: heights h = [4, 2, 0, 3, 2, 5, 1, 0, 2]. Compute the total water trapped between the bars.
h=[4,2,0,3,2,5,1,0,2]
print(sum(max(0,min(max(h[:i+1]),max(h[i:]))-h[i]) for i in range(len(h))))
What is printed?
  1. A. 31
  2. B. 12
  3. C. 14
  4. D. 21

Correct answer: B. 12

Water above each bar is min(left max, right max) minus its height. Summing the water level without subtracting the bar height counts the bars themselves, adding a stray constant is a careless slip, and using only the left running maximum overfills the right side.

More Coding Interview Problems questions

Exams that ask this topic