Programming & Development / April 19, 2025

Trapping Rain Water Problem in Java โ€” Optimal Two-Pointer Solution

trapping rain water Java two-pointer algorithm trapping rainwater problem explained coding interview questions Java O(n) space efficient solution

๐Ÿ“Œ Problem Statement

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

๐Ÿ“‰ Input Example

java

int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};

๐ŸŒง Expected Output:

6

๐Ÿ” Intuition Behind the Problem

Visualize bars of different heights as histogram pillars, where rainwater gets trapped in the "valleys" between them. The trapped water at any position is determined by the shorter of the tallest bars to the left and right minus the current height.

๐Ÿš€ Optimal Approach: Two-Pointer Technique

๐Ÿ”‘ Key Concepts:

  • Use two pointers, one starting from the left and the other from the right.
  • Track the maximum height seen so far from both sides: leftMax and rightMax.
  • At each step:
  • Move the pointer on the shorter side.
  • Compute the water that can be trapped at that position based on the min height of the max boundaries.

๐Ÿง  Time & Space Complexity

MetricValueTime ComplexityO(n)Space ComplexityO(1)

Efficient for large input arrays.

๐Ÿ’ป Java Code Implementation

java

public class TrappingRainWater {

    public int trap(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }

        int left = 0, right = height.length - 1;
        int leftMax = 0, rightMax = 0;
        int trappedWater = 0;

        while (left < right) {
            if (height[left] < height[right]) {
                if (height[left] >= leftMax) {
                    leftMax = height[left];
                } else {
                    trappedWater += leftMax - height[left];
                }
                left++;
            } else {
                if (height[right] >= rightMax) {
                    rightMax = height[right];
                } else {
                    trappedWater += rightMax - height[right];
                }
                right--;
            }
        }

        return trappedWater;
    }

    public static void main(String[] args) {
        TrappingRainWater solution = new TrappingRainWater();
        int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};
        System.out.println("Trapped water: " + solution.trap(height)); // Output: 6
    }
}

๐Ÿงช Explanation of the Output

For the input {0,1,0,2,1,0,1,3,2,1,2,1}:

  • Water is trapped at indices: 2, 4, 5, 6, 8, and 10.
  • The total is 6 units of water.

๐Ÿ› ๏ธ Real-World Applications

  • Landscape modeling and simulation
  • Reservoir and dam water level predictions
  • Game development (physics engines)

๐Ÿงต Bonus: Naive vs. Optimal

ApproachTimeSpaceNotesBrute-forceO(nยฒ)O(1)Scans left/right for every indexPrefix ArrayO(n)O(n)Uses extra space for prefix max arraysTwo-pointerO(n)O(1)Most efficient (used above) โœ…

โœ… Summary

  • The two-pointer approach is the most efficient way to solve the trapping rainwater problem.
  • It requires only one pass and uses constant space.
  • Great example of how to optimize a solution by using clever pointer movement.



Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex