Skip to content

Instantly share code, notes, and snippets.

@pradeep1991singh
Last active August 13, 2020 18:03
Show Gist options
  • Save pradeep1991singh/a23c0859af43a285164d37f712bc26f7 to your computer and use it in GitHub Desktop.
Save pradeep1991singh/a23c0859af43a285164d37f712bc26f7 to your computer and use it in GitHub Desktop.
Rain water trapped problem
// The idea is to use two pointer technique, pointer i & j for optimal solution
// run time complexity O(N)
// space time complexity O(1)
function trappedWater(height) {
if (height < 3) return 0;
// initialize trappedWater to zero
let trappedWater = 0;
// i starts from left which zero index
// and j starts from right which is last index
let i = 0;
let j = height.length - 1;
// initialize leftMax and rightMax to first value and last last
let leftMax = height[i];
let rightMax = height[j];
// iterate util i is smaller then j
while (i < j) {
if (height[i] < height[j]) {
// calculate left max and add trapped water to total
i++;
leftMax = Math.max(leftMax, height[i]);
trappedWater += leftMax - height[i];
} else {
// calculate right max and add trapped water to total
j--;
rightMax = Math.max(rightMax, height[j]);
trappedWater += rightMax - height[j];
}
}
// return total trapped water
return trappedWater;
}
var input = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1];
var output = trappedWater(input);
console.log(output);
// Output: 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment