Bird
Raised Fist0
DSA Javascriptprogramming~3 mins

Why Trapping Rain Water Using Stack in DSA Javascript?

Choose your learning style10 modes available
The Big Idea

Discover how a simple stack can solve a tricky water-trapping puzzle in just one pass!

The Scenario

Imagine you have a row of buildings with different heights after a rainstorm. You want to find out how much water is trapped between these buildings. Doing this by looking at each building and guessing the water trapped is like trying to count drops of water in a puddle by hand--slow and confusing.

The Problem

Manually checking each building and comparing it with others to find trapped water means repeating many checks and calculations. This is slow and easy to make mistakes, especially when buildings have varying heights and gaps.

The Solution

Using a stack helps keep track of buildings that can trap water efficiently. The stack remembers the positions of buildings that might form boundaries for water. This way, you only pass through the buildings once, calculating trapped water as you go, making the process fast and less error-prone.

Before vs After
✗ Before
let totalWater = 0;
for (let i = 0; i < heights.length; i++) {
  for (let j = i + 1; j < heights.length; j++) {
    // complex checks and calculations
  }
}
✓ After
const stack = [];
let totalWater = 0;
for (let i = 0; i < heights.length; i++) {
  while (stack.length && heights[i] > heights[stack[stack.length - 1]]) {
    // calculate trapped water
  }
  stack.push(i);
}
What It Enables

This method lets you quickly and accurately find how much water is trapped between buildings in just one pass.

Real Life Example

City planners can use this to estimate water accumulation between buildings after rain, helping design better drainage systems.

Key Takeaways

Manual checking is slow and error-prone.

Stack keeps track of building boundaries efficiently.

Calculates trapped water in one pass through the buildings.

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

  1. 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.
  2. 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.
  3. Final Answer:

    To keep track of bars that are not yet processed for water trapping -> Option B
  4. 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

  1. Step 1: Identify the correct data structure for stack in JavaScript

    JavaScript uses arrays as stacks by pushing and popping elements.
  2. 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.
  3. Final Answer:

    const stack = []; -> Option A
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    6 -> Option A
  4. 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

  1. Step 1: Analyze the while loop condition

    The condition uses >= which causes incorrect popping when heights are equal, leading to wrong trapped water calculation.
  2. Step 2: Correct the condition

    Changing >= to > ensures only strictly higher bars trigger popping, preserving correct boundaries.
  3. Final Answer:

    The comparison should be >, not >= in the while condition -> Option C
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    9 -> Option D
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard