← All problems · Arrays & Searching
Trapping Rain Water
Given nonnegative bar heights of unit width, return the total water trapped after rainfall. Assume the answer fits uint64_t.
Implement uint64_t trapped_water(const uint32_t *a, size_t n).
Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Track the highest wall from each side and process the lower boundary.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
uint64_t trapped_water(const uint32_t *a, size_t n)
{
if(n<3)return 0;
size_t l=0,r=n-1; uint32_t lm=0,rm=0; uint64_t total=0;
while(l<r){
if(a[l]<=a[r]){if(a[l]>lm)lm=a[l];total+=lm-a[l];++l;}
else{if(a[r]>rm)rm=a[r];total+=rm-a[r];--r;}
}
return total;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <climits>
std::uint64_t trapped_water(const std::uint32_t *a, std::size_t n)
{
if(n<3)return 0;
std::size_t l=0,r=n-1; std::uint32_t lm=0,rm=0; std::uint64_t total=0;
while(l<r){
if(a[l]<=a[r]){if(a[l]>lm)lm=a[l];total+=lm-a[l];++l;}
else{if(a[r]>rm)rm=a[r];total+=rm-a[r];--r;}
}
return total;
}
The lower side determines a safe water level. Two pointers avoid the two temporary maximum arrays in the supplied approach, using O(n) time and O(1) space.
solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
uint32_t a[]={3,0,6,2,5}, b[]={2,0,2}, c[]={1,2,3,4}, d[]={4,2,0,3,2,5};
CHECK(trapped_water(a,5)==6);
CHECK(trapped_water(b,3)==2);
CHECK(trapped_water(c,4)==0);
CHECK(trapped_water(NULL,0)==0);
CHECK(trapped_water(d,6)==9);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}