Data Structures & AlgorithmsVery hardProduct company OA

Rain water trapped between bars, computed with two pointers. What is printed?

Rain water trapped between bars, computed with two pointers. What is printed?
def water(h):
    l, r, lm, rm, w = 0, len(h) - 1, 0, 0, 0
    while l < r:
        if h[l] < h[r]:
            lm = max(lm, h[l]); w += lm - h[l]; l += 1
        else:
            rm = max(rm, h[r]); w += rm - h[r]; r -= 1
    return w
print(water([4, 0, 3, 1, 5, 0, 2, 0, 4]), water([5, 4, 3, 2, 1]), water([2, 0, 2, 0, 2]))
  1. A. 18 10 2
  2. B. 18 0 4
  3. C. 14 0 4
  4. D. 17 0 4

Correct answer: B. 18 0 4

Move the side with the lower bar: the water above it is limited by its own side's running maximum, because the other side is already known to have a bar at least that tall. [4,0,3,1,5,0,2,0,4]: left part 4+1+3 = 8, right part 4+2+4 = 10, total 18. A strictly decreasing profile traps nothing. [2,0,2,0,2] traps 2 + 2. 10 is the decreasing case computed as if the right edge were a wall of height 5.

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

Exams that ask this topic