Discover how a simple stack can solve a tricky rainwater puzzle faster than guessing!
Why Trapping Rain Water Using Stack in DSA C?
Imagine you have a row of buildings with different heights, and after it rains, you want to find out how much water gets trapped between them. Doing this by looking at each building and guessing the water trapped is like trying to count raindrops one by one on a big roof -- slow and confusing.
Manually checking each building and comparing it with every other building to find trapped water takes a lot of time and can easily lead to mistakes. It's like trying to solve a puzzle by testing every piece with every other piece -- it quickly becomes overwhelming and error-prone.
Using a stack helps us keep track of buildings in a smart way. We can quickly find where water can be trapped by remembering the heights and positions of buildings we have seen. This method is faster and less confusing, like having a helper who points out where water will collect as you walk along the buildings.
int trappedWater(int heights[], int size) {
int water = 0;
for (int i = 1; i < size - 1; i++) {
int maxLeft = 0, maxRight = 0;
for (int j = i; j >= 0; j--) maxLeft = (maxLeft > heights[j]) ? maxLeft : heights[j];
for (int j = i; j < size; j++) maxRight = (maxRight > heights[j]) ? maxRight : heights[j];
water += (maxLeft < maxRight ? maxLeft : maxRight) - heights[i];
}
return water;
}int trappedWater(int heights[], int size) {
int water = 0, top, current = 0;
int stack[size];
int stackTop = -1;
while (current < size) {
while (stackTop != -1 && heights[current] > heights[stack[stackTop]]) {
top = stack[stackTop--];
if (stackTop == -1) break;
int distance = current - stack[stackTop] - 1;
int bounded_height = (heights[current] < heights[stack[stackTop]] ? heights[current] : heights[stack[stackTop]]) - heights[top];
water += distance * bounded_height;
}
stack[++stackTop] = current++;
}
return water;
}This method lets us quickly and accurately calculate trapped rainwater in complex building arrangements, saving time and avoiding mistakes.
City planners use this idea to understand how water collects between buildings after rain, helping them design better drainage systems to prevent flooding.
Manual checking is slow and error-prone for trapping rainwater.
Stack helps track building heights efficiently to find trapped water.
This approach speeds up calculations and reduces mistakes.
Practice
Trapping Rain Water Using Stack algorithm?Solution
Step 1: Understand stack role 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 DQuick Check:
Stack tracks bars for trapping water [OK]
- Thinking stack stores water volume directly
- Assuming stack sorts the bars
- Believing stack reverses bar order
Solution
Step 1: Check stack declaration syntax
int stack[100]; int top = -1; declares an integer array with fixed size and initializes top to -1, which is correct for stack implementation.Step 2: Identify incorrect declarations
Options B, C, and D have wrong types or invalid initializations for stack and top pointer.Final Answer:
int stack[100]; int top = -1; -> Option AQuick Check:
Array + top = -1 is correct stack setup [OK]
- Using uninitialized or wrong top value
- Declaring stack as single int instead of array
- Using empty array syntax invalid in C
int height[] = {0,1,0,2,1,0,1,3,2,1,2,1};
int n = 12;
// Assume correct trapping rain water stack code runs here
int trapped = trappingRainWater(height, n);
printf("%d\n", trapped);Solution
Step 1: Understand the input heights
The array represents bar heights where water can be trapped between taller bars.Step 2: Calculate trapped water manually or recall known result
The known trapped water for this input is 6 units.Final Answer:
6 -> Option BQuick Check:
Standard example trapped water = 6 [OK]
- Miscounting trapped water units
- Confusing indexes or heights
- Assuming output is sum of heights
while (top != -1 && height[i] > height[stack[top]]) {
int topIndex = stack[top--];
int distance = i - stack[top] - 1;
int bounded_height = min(height[i], height[stack[top]]) - height[topIndex];
water += distance * bounded_height;
}Solution
Step 1: Check function usage
The code uses 'min' function but C standard library does not have 'min' by default; it needs a macro or function definition.Step 2: Verify other parts
Distance calculation and top decrement are correct; water variable usage depends on context but usually initialized.Final Answer:
Using 'min' function without including its definition or header -> Option AQuick Check:
min() undefined in C without custom code [OK]
- Assuming min() is built-in in C
- Miscalculating distance with wrong parentheses
- Forgetting to initialize water variable
{4, 2, 0, 3, 2, 5}, what is the total trapped rain water calculated using the stack method?Solution
Step 1: Analyze the heights for trapped water
Water trapped at each position i is max(0, min(left_max[i], right_max[i]) - height[i]), where left_max is tallest bar strictly to the left, right_max strictly to the right. Stack method yields same result.Step 2: Calculate trapped water step-by-step
- i=1: min(4,5)-2 = 2
- i=2: min(4,5)-0 = 4
- i=3: min(4,5)-3 = 1
- i=4: min(4,5)-2 = 2
Total: 2+4+1+2 = 9 units.Final Answer:
9 -> Option CQuick Check:
Total trapped water = 9 [OK]
- Double counting trapped water
- Ignoring zero height bars
- Misidentifying boundaries
Ready to prove it?
Pass the test and this pattern moves unknown
