Proficient Level

Implement the method trappedRainWater that calculates how much water can be trapped between bars.

Each value represents a bar height. Water can be held where a lower bar has taller boundaries on both sides.

The task is designed to test careful handling of edge cases, not only the most common input.

  • Use only the first size elements.
  • Bars with height 0 are allowed.
  • Return the total trapped units.

Example 1

Input
heights (int[]) = [0,1,0,2,1,0,1,3,2,1,2,1]
size (int) = 12
Returns (int) 6

Example 2

Input
heights (int[]) = [4,2,0,3,2,5]
size (int) = 6
Returns (int) 9

Example 3

Input
heights (int[]) = [1,2,3]
size (int) = 3
Returns (int) 0

Move the pointer on the side with the smaller height while tracking the best boundary seen from that side.

Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.