logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
25. Reverse Nodes in k-Group26. Remove Duplicates from Sorted Array27. Remove Element42. Trapping Rain Water51. N-Queens55. Jump Game80. Remove Duplicates from Sorted Array II88. Merge Sorted Array121. Best Time to Buy and Sell Stock122. Best Time to Buy and Sell Stock II189. Rotate Array274. H-Index
Code Scratch/leetcode/hard

42. Trapping Rain Water

2 min read
On this pageIntitution
IntitutionComplexityCode

# Intitution

To trap water between the bars, we need to know the maximum height to the left and to the right of each bar.

  • The water that a bar can trap = min(leftMax, rightMax) - heightAtBar, as long as this value is positive.

We traverse twice:

  1. Right to left to build an array of right max heights.
  2. Left to right to calculate trapped water using current height and right max.

# Complexity

Space ComplexityTime Complexity
O(N)\text{O}(N)O(N)O(N)\text{O}(N)O(N)

# Code

public int trap(int[] elevationHeights) {
    int n = elevationHeights.length;
 
    // Array to store the maximum height to the right of each bar
    int[] maxHeightToRight = new int[n];
 
    int maxSoFar = 0;
    // Traverse from right to left to fill maxHeightToRight
    for (int i = n - 1; i >= 0; --i) {
        maxHeightToRight[i] = maxSoFar;
        maxSoFar = Math.max(elevationHeights[i], maxSoFar);
    }
 
    int totalTrappedWater = 0;
    maxSoFar = 0; // Reuse for max height to the left
 
    // Traverse from left to right to compute trapped water
    for (int i = 0; i < n; ++i) {
        // Water that can be stored at current index
        int waterAtCurrent = Math.min(maxSoFar, maxHeightToRight[i]) - elevationHeights[i];
 
        // Only count if it's a positive amount of water
        if (waterAtCurrent > 0) {
            totalTrappedWater += waterAtCurrent;
        }
 
        maxSoFar = Math.max(elevationHeights[i], maxSoFar);
    }
 
    return totalTrappedWater;
}
 
←Previous27. Remove ElementNext→51. N-Queens

On this page

IntitutionComplexityCode