Bird
Raised Fist0
DSA Javascriptprogramming~10 mins

Trapping Rain Water Using Stack in DSA Javascript - Interactive Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to initialize the stack as an empty array.

DSA Javascript
const stack = [1];
Drag options to blanks, or click blank then click option'
A0
B{}
Cnull
D[]
Attempts:
3 left
💡 Hint
Common Mistakes
Using curly braces {} which creates an object, not an array.
Using null or 0 which are not arrays.
2fill in blank
medium

Complete the code to push the current index i onto the stack.

DSA Javascript
stack.[1](i);
Drag options to blanks, or click blank then click option'
Apush
Bshift
Cpop
Dunshift
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop which removes elements instead of adding.
Using shift or unshift which operate on the start of the array.
3fill in blank
hard

Fix the error in the while loop condition to check if the stack is not empty.

DSA Javascript
while (stack.[1] > 0 && height[i] > height[stack[stack.length - 1]]) {
Drag options to blanks, or click blank then click option'
Alength()
Blength
Ccount
Dsize
Attempts:
3 left
💡 Hint
Common Mistakes
Using length() which causes a runtime error.
Using size or count which are not valid for arrays.
4fill in blank
hard

Fill both blanks to calculate the distance and bounded height for trapped water.

DSA Javascript
const distance = i - stack[stack.length - 1] - [1];
const bounded_height = Math.min(height[i], height[stack[stack.length - 1]]) - height[[2]];
Drag options to blanks, or click blank then click option'
A1
B0
Ctop
Dstack.pop()
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 instead of 1 for distance calculation.
Using stack[stack.length - 1] instead of the popped index for height.
5fill in blank
hard

Fill all three blanks to update the total trapped water correctly.

DSA Javascript
water += distance * [1];
stack.[2](i);
let top = stack.[3]();
Drag options to blanks, or click blank then click option'
Abounded_height
Bpush
Cpop
Dheight[i]
Attempts:
3 left
💡 Hint
Common Mistakes
Using height[i] instead of bounded_height for water calculation.
Using pop instead of push to add index.
Using push instead of pop to remove index.

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