Trapping Rain Water Using Stack in DSA Java - Time & Space Complexity
We want to understand how the time needed to calculate trapped rain water changes as the input size grows.
Specifically, how does the number of operations grow when using a stack to solve this problem?
Analyze the time complexity of the following code snippet.
public int trap(int[] height) {
int water = 0, current = 0;
Stack<Integer> stack = new Stack<>();
while (current < height.length) {
while (!stack.isEmpty() && height[current] > height[stack.peek()]) {
int top = stack.pop();
if (stack.isEmpty()) break;
int distance = current - stack.peek() - 1;
int boundedHeight = Math.min(height[current], height[stack.peek()]) - height[top];
water += distance * boundedHeight;
}
stack.push(current++);
}
return water;
}
This code calculates how much rain water can be trapped between bars of different heights using a stack to track boundaries.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The outer while loop runs through each bar once, and the inner while loop pops bars from the stack when the current bar is taller.
- How many times: Each bar is pushed and popped at most once, so total operations related to stack are proportional to the number of bars.
As the number of bars increases, each bar is processed a limited number of times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (push and pop each bar once) |
| 100 | About 200 |
| 1000 | About 2000 |
Pattern observation: The operations grow roughly in a straight line with input size, doubling the bars roughly doubles the work.
Time Complexity: O(n)
This means the time to compute trapped water grows linearly with the number of bars.
[X] Wrong: "The inner while loop makes this algorithm O(n²) because it can run many times inside the outer loop."
[OK] Correct: Each bar is pushed and popped only once, so total inner loop executions across the whole run cannot exceed n, keeping the total operations linear.
Understanding this linear time solution shows you can use stacks smartly to solve tricky problems efficiently, a skill valued in many coding challenges.
"What if we replaced the stack with a simple nested loop approach? How would the time complexity change?"
Practice
Trapping Rain Water Using Stack algorithm?Solution
Step 1: Understand the role of the stack
The stack stores indices of bars that are waiting to find a right boundary to trap water.Step 2: Explain how the stack helps in trapping water
When a bar taller than the top of the stack is found, it means water can be trapped between bars. The stack helps find the left boundary and calculate trapped water.Final Answer:
To keep track of the indices of bars that are not yet processed for water trapping -> Option AQuick Check:
Stack stores indices for trapping water = C [OK]
- Thinking stack stores heights instead of indices
- Assuming stack sorts bars by height
- Confusing stack use with reversing the array
Solution
Step 1: Check Java generic syntax for Stack
Java uses generics with angle brackets and wrapper classes like Integer, not primitive int.Step 2: Identify correct initialization
Correct syntax isStack<Integer> stack = new Stack<>();which uses Integer wrapper and diamond operator.Final Answer:
Stack<Integer> stack = new Stack<>(); -> Option BQuick Check:
Use wrapper Integer and diamond operator = A [OK]
- Using primitive int inside generics
- Omitting generic type causing raw type warning
- Incorrect constructor syntax with generics
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) {
Stack<Integer> stack = new Stack<>();
int water = 0, current = 0;
while (current < height.length) {
while (!stack.isEmpty() && height[current] > height[stack.peek()]) {
int top = stack.pop();
if (stack.isEmpty()) break;
int distance = current - stack.peek() - 1;
int boundedHeight = Math.min(height[current], height[stack.peek()]) - height[top];
water += distance * boundedHeight;
}
stack.push(current++);
}
return water;
}Solution
Step 1: Trace the stack and water calculation
The code uses a stack to find boundaries and calculates trapped water step-by-step for the given heights.Step 2: Calculate trapped water for given input
For the input array, the total trapped water calculated is 6 units after processing all bars.Final Answer:
6 -> Option CQuick Check:
Trapped water for given heights = 6 [OK]
- Miscounting distance between bars
- Incorrect bounded height calculation
- Forgetting to break when stack is empty
public static int trap(int[] height) {
Stack<Integer> stack = new Stack<>();
int water = 0, current = 0;
while (current <= height.length) {
while (!stack.isEmpty() && height[current] > height[stack.peek()]) {
int top = stack.pop();
if (stack.isEmpty()) break;
int distance = current - stack.peek() - 1;
int boundedHeight = Math.min(height[current], height[stack.peek()]) - height[top];
water += distance * boundedHeight;
}
stack.push(current++);
}
return water;
}Solution
Step 1: Identify the loop boundary error
The condition 'current <= height.length' causes an attempt to access height[height.length], which is out of bounds.Step 2: Fix the loop condition
Changing it to 'current < height.length' prevents the out-of-bounds error and allows correct iteration.Final Answer:
Change 'current <= height.length' to 'current < height.length' to avoid ArrayIndexOutOfBoundsException -> Option DQuick Check:
Loop boundary must be less than array length = A [OK]
- Using <= instead of < in loop condition
- Replacing stack with wrong data structure
- Removing necessary inner loop
height = {4, 2, 0, 3, 2, 5}, what is the total amount of trapped rain water calculated by the stack-based algorithm?Solution
Step 1: Analyze trapped water between bars
Between bars of height 4 and 5, water is trapped over lower bars: 2, 0, 3, 2.Step 2: Calculate trapped water volume
Water level is min(4,5)=4. Water trapped = (4-2) + (4-0) + (4-3) + (4-2) = 2 + 4 + 1 + 2 = 9 units.Final Answer:
9 -> Option AQuick Check:
Sum trapped water between boundaries = 9 [OK]
- Using left boundary height only
- Ignoring right boundary taller bar
- Adding heights instead of differences
Ready to prove it?
Pass the test and this pattern moves unknown
