Bird
Raised Fist0
DSA C++programming~20 mins

Trapping Rain Water Using Stack in DSA C++ - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Trapping Rain Water Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Trapping Rain Water Calculation
What is the output of the following C++ code that calculates trapped rain water using a stack?
DSA C++
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

int trap(vector<int>& height) {
    int n = height.size();
    stack<int> st;
    int water = 0;
    for (int i = 0; i < n; i++) {
        while (!st.empty() && height[i] > height[st.top()]) {
            int top = st.top();
            st.pop();
            if (st.empty()) break;
            int distance = i - st.top() - 1;
            int bounded_height = min(height[i], height[st.top()]) - height[top];
            water += distance * bounded_height;
        }
        st.push(i);
    }
    return water;
}

int main() {
    vector<int> height = {0,1,0,2,1,0,1,3,2,1,2,1};
    cout << trap(height) << endl;
    return 0;
}
A8
B6
C7
D5
Attempts:
2 left
💡 Hint
Think about how the stack helps find boundaries to trap water between bars.
🧠 Conceptual
intermediate
1:30remaining
Understanding Stack Usage in Trapping Rain Water
Why does the stack help in solving the trapping rain water problem efficiently?
AIt stores the height values to calculate total water directly.
BIt sorts the bars in ascending order to calculate water.
CIt keeps track of indices of bars to find boundaries for trapped water.
DIt reverses the array to simplify calculations.
Attempts:
2 left
💡 Hint
Think about how boundaries are found between bars.
🔧 Debug
advanced
2:00remaining
Identify the Error in Trapping Rain Water Code
What error will the following code produce when run?
DSA C++
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

int trap(vector<int>& height) {
    int n = height.size();
    stack<int> st;
    int water = 0;
    for (int i = 0; i < n; i++) {
        while (!st.empty() && height[i] > height[st.top()]) {
            int top = st.top();
            st.pop();
            if (st.empty()) break;
            int distance = i - st.top() - 1;
            int bounded_height = min(height[i], height[st.top()]) - height[top];
            water += distance * bounded_height;
        }
        st.push(i);
    }
    return water;
}

int main() {
    vector<int> height = {4,2,0,3,2,5};
    cout << trap(height) << endl;
    return 0;
}
ACompilation error due to missing semicolon
BOutput: 7
COutput: 9
DRuntime error: out_of_range exception
Attempts:
2 left
💡 Hint
Check the loop boundary condition carefully.
❓ Predict Output
advanced
2:00remaining
Output of Modified Trapping Rain Water Code
What is the output of this modified C++ code snippet?
DSA C++
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

int trap(vector<int>& height) {
    int n = height.size();
    stack<int> st;
    int water = 0;
    for (int i = 0; i < n; i++) {
        while (!st.empty() && height[i] >= height[st.top()]) {
            int top = st.top();
            st.pop();
            if (st.empty()) break;
            int distance = i - st.top() - 1;
            int bounded_height = min(height[i], height[st.top()]) - height[top];
            water += distance * bounded_height;
        }
        st.push(i);
    }
    return water;
}

int main() {
    vector<int> height = {4,2,0,3,2,5};
    cout << trap(height) << endl;
    return 0;
}
A9
B7
C8
D10
Attempts:
2 left
💡 Hint
Note the use of '>=' in the while condition instead of '>'.
🚀 Application
expert
3:00remaining
Maximum Water Trapped in a Large Histogram
Given a histogram with heights: [5,2,1,2,1,5,3,2,4,1,2,3,1,2,1], what is the maximum amount of water trapped using the stack method?
A28
B27
C26
D25
Attempts:
2 left
💡 Hint
Visualize the bars and calculate trapped water between boundaries using the stack approach.

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
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 order of the bars

Solution

  1. 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.
  2. Step 2: Explain why other options are incorrect

    The stack does not store water amount or sort bars; it helps track bars for water calculation.
  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 = A [OK]
Hint: Stack holds bars waiting for right boundary [OK]
Common Mistakes:
  • Thinking stack stores water amount
  • Assuming stack sorts bars
  • Confusing stack with array for heights
2. Which of the following C++ code snippets correctly declares a stack to be used for trapping rain water indices?
easy
A. std::stack<int> st;
B. stack<int> st = new stack<int>();
C. std::stack st<int>;
D. stack<int> st();

Solution

  1. Step 1: Check correct C++ stack declaration syntax

    Correct syntax is std::stack<int> st; to declare a stack of integers.
  2. Step 2: Identify errors in other options

    stack<int> st = new stack<int>(); uses incorrect syntax with 'new'; C has wrong template placement; D declares a function, not a stack.
  3. Final Answer:

    std::stack<int> st; -> Option A
  4. Quick Check:

    Correct stack declaration = B [OK]
Hint: Use std::stack<int> st; to declare stack [OK]
Common Mistakes:
  • Using 'new' keyword incorrectly
  • Wrong template syntax
  • Declaring function instead of stack
3. What is the output of the following C++ code snippet that uses stack to calculate trapped rain water?
int height[] = {0,1,0,2,1,0,1,3,2,1,2,1};
int n = 12;
std::stack<int> st;
int water = 0;
for (int i = 0; i < n; i++) {
  while (!st.empty() && height[i] > height[st.top()]) {
    int top = st.top();
    st.pop();
    if (st.empty()) break;
    int distance = i - st.top() - 1;
    int bounded_height = std::min(height[i], height[st.top()]) - height[top];
    water += distance * bounded_height;
  }
  st.push(i);
}
std::cout << water << std::endl;
medium
A. 8
B. 5
C. 6
D. 7

Solution

  1. Step 1: Trace the stack operations and water calculation

    The code calculates trapped water for the given heights array using stack logic. The total trapped water is 6 units.
  2. Step 2: Verify calculations with known example

    This is a classic example where trapped water is 6 units, matching the output of the code.
  3. Final Answer:

    6 -> Option C
  4. Quick Check:

    Trapped water = 6 [OK]
Hint: Classic example traps 6 units water [OK]
Common Mistakes:
  • Miscounting distance between bars
  • Wrong bounded height calculation
  • Ignoring empty stack break condition
4. Identify the error in the following C++ code snippet for trapping rain water using stack:
std::stack<int> st;
int water = 0;
for (int i = 0; i < height.size(); i++) {
  while (!st.empty() && height[i] >= height[st.top()]) {
    int top = st.top();
    st.pop();
    if (st.empty()) break;
    int distance = i - st.top() - 1;
    int bounded_height = std::min(height[i], height[st.top()]) - height[top];
    water += distance * bounded_height;
  }
  st.push(i);
}
std::cout << water << std::endl;
medium
A. No break condition inside while loop
B. Missing initialization of water variable
C. Stack should store heights, not indices
D. Using >= instead of > in while condition causes incorrect water calculation

Solution

  1. Step 1: Analyze the while loop condition

    The condition uses >= which causes popping bars of equal height, leading to incorrect trapped water calculation.
  2. Step 2: Explain correct condition and impact

    Using > ensures only bars lower than current are popped, preserving correct boundaries for water trapping.
  3. Final Answer:

    Using >= instead of > in while condition causes incorrect water calculation -> Option D
  4. Quick Check:

    Use > not >= in while condition [OK]
Hint: Use > not >= in while condition [OK]
Common Mistakes:
  • Using >= instead of > in while condition
  • Storing heights instead of indices in stack
  • Forgetting break when stack is empty
5. Given the heights array {4, 2, 0, 3, 2, 5}, what is the total trapped rain water calculated using the stack approach?
hard
A. 8
B. 7
C. 9
D. 6

Solution

  1. Step 1: Calculate trapped water between bars using stack logic

    Between bars, trapped water units are: 2 units between 4 and 3, 1 unit between 3 and 5, and 5 units between 2 and 5, totaling 8 units.
  2. Step 2: Sum trapped water units

    Sum of trapped water is 8 units for the given array.
  3. Final Answer:

    8 -> Option A
  4. Quick Check:

    Trapped water total = 8 [OK]
Hint: Sum water trapped between boundaries carefully [OK]
Common Mistakes:
  • Ignoring zero height bars
  • Miscounting trapped water between bars
  • Not considering both left and right boundaries
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