📖 Scenario: Imagine you have a row of walls of different heights, like buildings in a city skyline. When it rains, water gets trapped between these walls. Your task is to find out how much water is trapped after the rain stops.
🎯 Goal: Build a program that uses a stack to calculate the total amount of trapped rain water between walls represented by an array of heights.
📋 What You'll Learn
Create an array called heights with the exact values [0,1,0,2,1,0,1,3,2,1,2,1]
Create a variable called stack initialized as an empty array
Create a variable called waterTrapped initialized to 0
Use a for loop with variable i to iterate over heights
Inside the loop, use a while loop to pop from stack and calculate trapped water using the stack method
Print the total trapped water using console.log(waterTrapped)
💡 Why This Matters
🌍 Real World
Calculating trapped rain water is similar to solving problems in civil engineering and urban planning where water drainage and accumulation need to be understood.
💼 Career
Understanding stack-based algorithms and problem-solving techniques is important for software engineering roles that involve data structure optimization and algorithm design.
Progress0 / 4 steps
1
Create the heights array
Create an array called heights with these exact values: [0,1,0,2,1,0,1,3,2,1,2,1]
DSA Javascript
Hint
Use const heights = [...] to create the array with the exact numbers.
2
Initialize stack and waterTrapped variables
Create a variable called stack initialized as an empty array and a variable called waterTrapped initialized to 0
DSA Javascript
Hint
Use const stack = []; and let waterTrapped = 0; to set up your variables.
3
Implement the stack logic to calculate trapped water
Use a for loop with variable i to iterate over heights. Inside the loop, use a while loop to pop from stack while heights[i] is greater than heights[stack[stack.length - 1]]. Calculate the trapped water for each popped index and add it to waterTrapped. Push i to stack at the end of each iteration.
DSA Javascript
Hint
Use a for loop to go through each height. Inside, use a while loop to pop from the stack when current height is greater than the height at the top of the stack. Calculate trapped water using distance and bounded height formulas.
4
Print the total trapped water
Print the value of waterTrapped using console.log(waterTrapped)
DSA Javascript
Hint
Use console.log(waterTrapped) to show the total trapped water.
Practice
(1/5)
1. What is the main purpose of using a stack in the Trapping Rain Water Using Stack algorithm?
easy
A. To store the total amount of trapped water directly
B. To keep track of bars that are not yet processed for water trapping
C. To sort the heights of bars in ascending order
D. To reverse the array of bar heights
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 B
Quick Check:
Stack tracks bars for trapping water [OK]
Hint: Stack holds indices of bars waiting for right boundary [OK]
Common Mistakes:
Thinking stack stores water volume directly
Assuming stack sorts the bars
Believing stack reverses the array
2. Which of the following is the correct way to initialize an empty stack in JavaScript for the trapping rain water problem?
easy
A. const stack = [];
B. const stack = {};
C. const stack = null;
D. const stack = new Stack();
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 A
Quick Check:
Empty array for stack [OK]
Hint: Use empty array [] as stack in JavaScript [OK]
Common Mistakes:
Using object {} instead of array
Assuming Stack class exists by default
Initializing stack as null
3. What will be the output of the following code snippet that uses stack to calculate trapped rain water?
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));
medium
A. 6
B. 5
C. 7
D. 8
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 A
Quick Check:
Classic trapping rain water example = 6 [OK]
Hint: Classic example height array traps 6 units water [OK]
Common Mistakes:
Miscounting trapped water units
Ignoring stack empty check
Wrong distance or bounded height calculation
4. Identify the error in the following code snippet for trapping rain water using stack:
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;
}
medium
A. The distance calculation is incorrect
B. The stack should be initialized as an object, not array
C. The comparison should be >, not >= in the while condition
D. The water variable should be reset inside the loop
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 C
Quick Check:
Use > in while condition to avoid wrong pops [OK]
Hint: Use >, not >=, to avoid popping equal height bars [OK]
Common Mistakes:
Using >= causes incorrect water calculation
Initializing stack as object instead of array
Resetting water inside loop wrongly
5. Given the heights array [4, 2, 0, 3, 2, 5], what is the total trapped rain water calculated using the stack method?
hard
A. 6
B. 7
C. 8
D. 9
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 D
Quick Check:
Sum trapped water units = 9 [OK]
Hint: Sum water between boundaries carefully for correct total [OK]
Common Mistakes:
Miscounting trapped water units
Ignoring zero height bars
Wrong boundary identification
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.