Trapping Rain Water Problem in DSA Java - Time & Space Complexity
We want to understand how the time needed to solve the Trapping Rain Water problem changes as the input size grows.
Specifically, how the number of operations depends on the number of bars in the elevation map.
Analyze the time complexity of the following code snippet.
public int trap(int[] height) {
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;
}
This code calculates how much water can be trapped between bars represented by the array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that moves two pointers from both ends towards the center.
- How many times: Each element is visited at most once by either the left or right pointer, so the loop runs roughly n times where n is the array length.
As the number of bars increases, the number of steps grows roughly the same as the number of bars.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The operations grow linearly with input size; doubling the bars roughly doubles the work.
Time Complexity: O(n)
This means the time to solve the problem grows directly in proportion to the number of bars.
[X] Wrong: "Because there are nested conditions, the time complexity must be quadratic O(n²)."
[OK] Correct: The loop moves pointers inward without repeating the same elements multiple times, so each element is processed once, keeping the time linear.
Understanding this linear time solution shows you can optimize problems by clever pointer use instead of brute force, a skill valued in real coding challenges.
"What if we used a nested loop to check every pair of bars instead of two pointers? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem statement
The problem asks to calculate how much water can be trapped between bars of different heights after it rains.Step 2: Identify the goal
The goal is to find the total volume of trapped water, not just heights or counts of bars.Final Answer:
The total amount of water that can be trapped between the bars after raining -> Option AQuick Check:
Trapping rain water = total trapped water volume [OK]
- Confusing trapped water with max bar height
- Counting bars taller than neighbors instead of water
- Calculating minimum height instead of trapped water
Solution
Step 1: Check Java array initialization syntax
In Java, arrays are initialized with curly braces {} and type declaration like int[].Step 2: Validate each option
int[] heights = {4, 2, 0, 3, 2, 5}; uses correct syntax: int[] heights = {4, 2, 0, 3, 2, 5}; Options B, C, and D use invalid syntax.Final Answer:
int[] heights = {4, 2, 0, 3, 2, 5}; -> Option DQuick Check:
Java array init uses {} with type[] [OK]
- Using square brackets [] without type[]
- Using parentheses () instead of braces {}
- Trying to initialize array with new int(size) and values together
int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};
System.out.println(trap(height));
public static int trap(int[] height) {
int left = 0, right = height.length - 1;
int leftMax = 0, rightMax = 0, water = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) leftMax = height[left];
else water += leftMax - height[left];
left++;
} else {
if (height[right] >= rightMax) rightMax = height[right];
else water += rightMax - height[right];
right--;
}
}
return water;
}Solution
Step 1: Understand two-pointer approach
We use two pointers left and right, track max heights on both sides, and add trapped water where possible.Step 2: Trace the code with given input
For input {0,1,0,2,1,0,1,3,2,1,2,1}, the trapped water calculated is 6 units.Final Answer:
6 -> Option BQuick Check:
Two-pointer trap calculation = 6 [OK]
- Not updating leftMax and rightMax correctly
- Adding negative water amounts
- Confusing left and right pointer movements
public static int trap(int[] height) {
int left = 0, right = height.length - 1;
int leftMax = 0, rightMax = 0, water = 0;
while (left <= right) {
if (height[left] < height[right]) {
if (height[left] > leftMax) leftMax = height[left];
else water += leftMax - height[left];
left++;
} else {
if (height[right] > rightMax) rightMax = height[right];
else water += rightMax - height[right];
right--;
}
}
return water;
}Solution
Step 1: Analyze loop condition impact
The loop uses 'left <= right', which causes double counting when left == right.Step 2: Correct loop condition
Changing to 'left < right' prevents overlapping pointers and avoids incorrect water calculation.Final Answer:
The loop condition should be 'left < right' instead of 'left <= right' -> Option CQuick Check:
Loop condition 'left < right' avoids overlap [OK]
- Using <= causes double counting at same index
- Changing comparison operators incorrectly
- Initializing max heights incorrectly
{3, 0, 2, 0, 4}, what is the total trapped rain water? Explain how the trapped water is calculated step-by-step.Solution
Step 1: Calculate leftMax and rightMax arrays
leftMax = [3, 3, 3, 3, 4], rightMax = [4, 4, 4, 4, 4]Step 2: Calculate trapped water at each index
Water trapped = min(leftMax[i], rightMax[i]) - height[i] = [0, 3, 1, 3, 0] Sum = 0 + 3 + 1 + 3 + 0 = 7Step 3: Re-check calculation for correctness
At index 1: min(3,4)-0=3 At index 2: min(3,4)-2=1 At index 3: min(3,4)-0=3 Sum = 7 units trapped waterFinal Answer:
7 -> Option AQuick Check:
Sum trapped water = 7 units [OK]
- Forgetting to take minimum of leftMax and rightMax
- Subtracting height incorrectly
- Not summing trapped water at all indices
Ready to prove it?
Pass the test and this pattern moves unknown
