AlgoMaster Logo

Trapping Rain Water

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

The brute force approach involves iterating over each element in the height array and for each element, calculating the maximum water that can be trapped above it by determining the highest bars to its left and right. This is done in three loops: one for the current index, and two for finding the left and right max bars.

Intuition:

  • For each bar, calculate the maximum height of the bars to the left and right.
  • The water level on top of the current bar is the minimum of these two heights minus the height of the current bar.
  • Sum this for each bar.

Code:

2. Dynamic Programming

The dynamic programming approach involves precomputing the maximum height to the left and right of each element using separate arrays. This eliminates the need for nested loops, as in the brute force approach.

Intuition:

  • Use two arrays, leftMax and rightMax.
  • leftMax[i] stores the maximum height from the start to index i.
  • rightMax[i] stores the maximum height from index i to the end.
  • Calculate the trapped water for each element as before, but use precomputed arrays.

Code:

3. Two Pointers

The two-pointers technique improves upon the dynamic programming solution by using two pointers that traverse the height array from both ends. It uses variables to store current left and right max heights, allowing us to calculate the trapped water more efficiently without additional space.

Intuition:

  • Initialize two pointers, left at the start and right at the end of the array.
  • Maintain two variables leftMax and rightMax for the maximum heights encountered from the left and right, respectively.
  • Move the pointers towards each other, updating trapped water based on which of leftMax and rightMax is smaller.

Code: