📖 Scenario: Imagine you have a row of walls of different heights. When it rains, water gets trapped between these walls. You want to find out how much water is trapped in total.
🎯 Goal: Build a program that calculates the total amount of water trapped between walls represented by an array of heights.
📋 What You'll Learn
Create an array called height with exact values representing wall heights
Create two arrays called leftMax and rightMax to store maximum heights from left and right
Use loops to fill leftMax and rightMax arrays
Calculate total trapped water using the height, leftMax, and rightMax arrays
Print the total trapped water
💡 Why This Matters
🌍 Real World
This problem models how water accumulates in valleys between walls or buildings, useful in civil engineering and urban planning.
💼 Career
Understanding this problem helps in algorithm design and problem-solving skills, important for software engineering interviews and roles involving data structures.
Progress0 / 4 steps
1
Create the height array
Create an integer array called height with these exact values: 0,1,0,2,1,0,1,3,2,1,2,1
DSA C++
Hint
Use int height[] = {0,1,0,2,1,0,1,3,2,1,2,1}; to create the array and calculate its size with n.
2
Create leftMax and rightMax arrays
Create two integer arrays called leftMax and rightMax of size n. Initialize all elements to 0.
DSA C++
Hint
Use int leftMax[n] = {0}; and int rightMax[n] = {0}; to create and initialize the arrays.
3
Fill leftMax and rightMax arrays
Use a for loop with variable i from 0 to n-1 to fill leftMax where each element is the maximum height from the left up to index i. Then use a for loop with variable i from n-1 down to 0 to fill rightMax where each element is the maximum height from the right up to index i.
DSA C++
Hint
Use loops to fill leftMax and rightMax by comparing current height with previous max.
4
Calculate and print total trapped water
Create an integer variable totalWater and set it to 0. Use a for loop with variable i from 0 to n-1 to add the trapped water at each index calculated as the minimum of leftMax[i] and rightMax[i] minus height[i]. Then print totalWater.
DSA C++
Hint
Calculate trapped water at each index as the smaller of leftMax and rightMax minus height, then sum it up.
Practice
(1/5)
1. What does the Trapping Rain Water problem ask you to find given an array of heights?
easy
A. The total amount of water that can be trapped between the bars after raining
B. The highest bar in the array
C. The number of bars taller than a given height
D. The sum of all bar heights
Solution
Step 1: Understand the problem context
The problem gives an array representing heights of bars and asks how much water can be trapped between them after it rains.
Step 2: Identify the goal
The goal is to calculate the total trapped water volume, not just heights or counts.
Final Answer:
The total amount of water that can be trapped between the bars after raining -> Option A
Quick Check:
Trapping rain water = total trapped water [OK]
Hint: Think of bars as walls holding water in gaps [OK]
Common Mistakes:
Confusing trapped water with highest bar height
Summing bar heights instead of trapped water
Counting bars taller than a certain height
2. Which of the following C++ code snippets correctly initializes a vector named heights with values {0,1,0,2,1,0,1,3,2,1,2,1}?
easy
A. std::vector<int> heights = (0,1,0,2,1,0,1,3,2,1,2,1);
B. std::vector<int> heights = {0,1,0,2,1,0,1,3,2,1,2,1};
C. vector<int> heights(0,1,0,2,1,0,1,3,2,1,2,1);
D. std::vector heights = {0,1,0,2,1,0,1,3,2,1,2,1};
Solution
Step 1: Check vector initialization syntax
In C++, std::vector<int> can be initialized with curly braces and values inside, like {0,1,...}.
Step 2: Identify correct syntax
std::vector<int> heights = {0,1,0,2,1,0,1,3,2,1,2,1}; uses correct syntax with std::vector<int> and brace initialization.
Final Answer:
std::vector<int> heights = {0,1,0,2,1,0,1,3,2,1,2,1}; -> Option B
Quick Check:
Correct vector init uses braces and type [OK]
Hint: Use curly braces {} for vector initialization [OK]
Common Mistakes:
Omitting std:: before vector
Using parentheses instead of braces
Not specifying vector type
3. What is the output of the following C++ code snippet that calculates trapped rain water?
std::vector<int> height = {0,1,0,2,1,0,1,3,2,1,2,1};
int n = height.size();
int left_max = 0, right_max = 0, left = 0, right = n - 1, water = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= left_max) left_max = height[left];
else water += left_max - height[left];
left++;
} else {
if (height[right] >= right_max) right_max = height[right];
else water += right_max - height[right];
right--;
}
}
std::cout << water << std::endl;
medium
A. 6
B. 5
C. 7
D. 8
Solution
Step 1: Understand two-pointer approach
Two pointers move inward, tracking max heights on left and right, accumulating trapped water where current height is less than max.
Step 2: Trace the code logic on given input
For input {0,1,0,2,1,0,1,3,2,1,2,1}, the total trapped water calculated is 6 units.
Final Answer:
6 -> Option A
Quick Check:
Two-pointer trapped water = 6 [OK]
Hint: Use two pointers and track max heights from both ends [OK]
Common Mistakes:
Not updating left_max or right_max correctly
Adding negative water amounts
Confusing left and right pointer moves
4. Identify the bug in this C++ code snippet for trapping rain water and select the fix:
std::vector<int> height = {4,2,0,3,2,5};
int n = height.size();
int left_max = 0, right_max = 0, left = 0, right = n - 1, water = 0;
while (left <= right) {
if (height[left] < height[right]) {
if (height[left] > left_max) left_max = height[left];
else water += left_max - height[left];
left++;
} else {
if (height[right] > right_max) right_max = height[right];
else water += right_max - height[right];
right--;
}
}
std::cout << water << std::endl;
medium
A. Initialize left_max and right_max to height[0] and height[n-1] respectively
B. Use '>=' instead of '>' when updating left_max and right_max
C. Change while condition to 'left < right' to avoid double counting
D. No bug, code is correct
Solution
Step 1: Analyze loop condition impact
The loop uses 'left <= right', which causes the middle element to be processed twice, leading to incorrect water calculation.
Step 2: Fix loop condition
Changing condition to 'left < right' ensures each element is processed once, preventing double counting.
Final Answer:
Change while condition to 'left < right' to avoid double counting -> Option C
Hint: Use strict less than in two-pointer loops [OK]
Common Mistakes:
Using <= instead of < in while loop
Not updating max heights correctly
Assuming no bug without testing
5. Given an array representing heights of bars, how would you modify the standard trapping rain water algorithm to handle very large input efficiently without extra space?
hard
A. Use recursion to calculate trapped water for each bar
B. Precompute left_max and right_max arrays and sum trapped water using extra arrays
C. Sort the array and calculate trapped water based on sorted positions
D. Use two pointers from both ends, track max heights, and calculate trapped water on the fly
Solution
Step 1: Understand space constraints
Precomputing arrays uses extra space O(n), which is costly for very large inputs.
Step 2: Use two-pointer approach for O(1) space
Two pointers from both ends track max heights and calculate trapped water without extra arrays, making it efficient.
Final Answer:
Use two pointers from both ends, track max heights, and calculate trapped water on the fly -> Option D
Quick Check:
Two-pointer approach = efficient O(1) space [OK]
Hint: Two pointers save space by avoiding extra arrays [OK]
Common Mistakes:
Using extra arrays causing high memory use
Sorting changes bar order, invalid for trapping water
Recursion adds overhead and complexity
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.