Trapping Rain Water Using Stack in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to calculate trapped rain water changes as the input size grows.
How does the number of steps grow when we use a stack to solve this problem?
Analyze the time complexity of the following code snippet.
function trap(height) {
let stack = [];
let water = 0;
for (let i = 0; i < height.length; i++) {
while (stack.length && height[i] > height[stack[stack.length - 1]]) {
let top = stack.pop();
if (!stack.length) break;
let distance = i - stack[stack.length - 1] - 1;
let boundedHeight = Math.min(height[i], height[stack[stack.length - 1]]) - height[top];
water += distance * boundedHeight;
}
stack.push(i);
}
return water;
}
This code calculates how much rainwater can be trapped between bars using a stack to track boundaries.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs once over all bars.
- Nested operation: The while-loop pops from the stack when current bar is higher than the top of stack.
- How many times: Each bar is pushed and popped at most once, so total stack operations are proportional to input size.
As the number of bars increases, the for-loop runs once per bar, and the while-loop pops bars only when needed.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 stack operations |
| 100 | About 200 stack operations |
| 1000 | About 2000 stack operations |
Pattern observation: The total operations grow roughly in a straight line with input size.
Time Complexity: O(n)
This means the time to compute trapped water grows linearly with the number of bars.
[X] Wrong: "Because there is a nested while-loop inside the for-loop, the time complexity must be O(n²)."
[OK] Correct: Each bar is pushed and popped only once, so the total number of stack operations is at most 2n, making the overall time linear, not quadratic.
Understanding this linear time solution shows you can use stacks smartly to solve problems efficiently, a skill valued in many coding challenges.
"What if we used a simple nested loop without a stack? How would the time complexity change?"
Practice
Trapping Rain Water Using Stack algorithm?Solution
Step 1: Understand the role of stack in the algorithm
The stack stores indices of bars that are waiting to find a right boundary to trap water.Step 2: Clarify what the stack does not do
The stack does not store water amounts or sort bars; it helps find boundaries for trapped water.Final Answer:
To keep track of bars that are not yet processed for water trapping -> Option BQuick Check:
Stack tracks bars for trapping water [OK]
- Thinking stack stores water volume directly
- Assuming stack sorts the bars
- Believing stack reverses the array
Solution
Step 1: Identify the correct data structure for stack in JavaScript
JavaScript uses arrays as stacks by pushing and popping elements.Step 2: Check each option
const stack = []; initializes an empty array, which works as a stack. const stack = {}; is an object, not a stack. const stack = null; is null, no stack. const stack = new Stack(); assumes a Stack class which is not built-in.Final Answer:
const stack = []; -> Option AQuick Check:
Empty array for stack [OK]
- Using object {} instead of array
- Assuming Stack class exists by default
- Initializing stack as null
const height = [0,1,0,2,1,0,1,3,2,1,2,1];
function trap(height) {
let stack = [];
let water = 0;
for (let i = 0; i < height.length; i++) {
while (stack.length && height[i] > height[stack[stack.length - 1]]) {
let top = stack.pop();
if (!stack.length) break;
let distance = i - stack[stack.length - 1] - 1;
let boundedHeight = Math.min(height[i], height[stack[stack.length - 1]]) - height[top];
water += distance * boundedHeight;
}
stack.push(i);
}
return water;
}
console.log(trap(height));Solution
Step 1: Understand the input and algorithm flow
The input array represents bar heights. The stack-based algorithm calculates trapped water by finding boundaries and distances.Step 2: Trace the code logic mentally
The code correctly calculates trapped water for the given heights, which is a classic example resulting in 6 units of water trapped.Final Answer:
6 -> Option AQuick Check:
Classic trapping rain water example = 6 [OK]
- Miscounting trapped water units
- Ignoring stack empty check
- Wrong distance or bounded height calculation
function trap(height) {
let stack = [];
let water = 0;
for (let i = 0; i < height.length; i++) {
while (stack.length && height[i] >= height[stack[stack.length - 1]]) {
let top = stack.pop();
if (!stack.length) break;
let distance = i - stack[stack.length - 1] - 1;
let boundedHeight = Math.min(height[i], height[stack[stack.length - 1]]) - height[top];
water += distance * boundedHeight;
}
stack.push(i);
}
return water;
}Solution
Step 1: Analyze the while loop condition
The condition uses >= which causes incorrect popping when heights are equal, leading to wrong trapped water calculation.Step 2: Correct the condition
Changing >= to > ensures only strictly higher bars trigger popping, preserving correct boundaries.Final Answer:
The comparison should be >, not >= in the while condition -> Option CQuick Check:
Use > in while condition to avoid wrong pops [OK]
- Using >= causes incorrect water calculation
- Initializing stack as object instead of array
- Resetting water inside loop wrongly
[4, 2, 0, 3, 2, 5], what is the total trapped rain water calculated using the stack method?Solution
Step 1: Visualize the bars and trapped water
Bars heights: 4,2,0,3,2,5. Water trapped between bars is calculated by stack method considering boundaries and distances.Step 2: Calculate trapped water step-by-step
Water at index 1: 2, index 2: 4, index 3: 1, index 4: 2, total 9 units.Final Answer:
9 -> Option DQuick Check:
Sum trapped water units = 9 [OK]
- Miscounting trapped water units
- Ignoring zero height bars
- Wrong boundary identification
Ready to prove it?
Pass the test and this pattern moves unknown
