Data Structures & AlgorithmsVery hardCodeforces Div2 D · GATE CS

Bars of heights [4, 2, 0, 3, 2, 5, 1, 0, 3] (width 1 each) hold rainwater between them. How many units of water are trapped in total?

  1. A. 14
  2. B. 15
  3. C. 10
  4. D. 13

Correct answer: A. 14

Water above position i is min(max height to its left, max height to its right) − h[i]. The two-pointer form moves the side with the smaller maximum inward. Using only the global maximum as the cap ignores that the wall on the other side may be lower.

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

Exams that ask this topic