Trapping Rain Water Problem in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to solve the Trapping Rain Water problem changes as the input size grows.
Specifically, how does the number of steps grow when we have more bars in the elevation map?
Analyze the time complexity of the following code snippet.
function trap(height) {
let left = 0, right = height.length - 1;
let leftMax = 0, rightMax = 0;
let water = 0;
while (left <= right) {
if (height[left] <= height[right]) {
if (height[left] > leftMax) leftMax = height[left];
else water += leftMax - height[left];
left++;
} else {
if (height[right] > rightMax) rightMax = height[right];
else water += rightMax - height[right];
right--;
}
}
return water;
}
This code calculates how much water can be trapped between bars represented by the array height.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
whileloop that moves two pointers across the array. - How many times: The loop runs at most
ntimes, wherenis the length of the array.
As the number of bars increases, the loop runs once for each bar, so the steps grow directly with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The number of steps grows linearly as input size grows.
Time Complexity: O(n)
This means the time to solve the problem grows in direct proportion to the number of bars.
[X] Wrong: "Because there are nested if-else statements, the time complexity must be quadratic O(n²)."
[OK] Correct: The if-else statements are inside a single loop that runs once per element, not nested loops. So the total steps grow linearly, not squared.
Understanding this problem's time complexity helps you explain efficient pointer techniques and shows you can analyze how loops affect performance.
"What if we used two nested loops to check every pair of bars? How would the time complexity change?"
Practice
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 volume of water trapped between the bars, not just heights or counts.Final Answer:
The total amount of water that can be trapped between the bars after raining -> Option BQuick Check:
Trapping Rain Water = Total trapped water [OK]
- Confusing trapped water with maximum bar height
- Counting bars taller than neighbors instead of trapped water
- Calculating minimum height instead of trapped water volume
Solution
Step 1: Check array initialization syntax
In JavaScript, arrays are initialized using square brackets []. const heights = [4, 2, 0, 3, 2, 5]; uses this correct syntax.Step 2: Identify incorrect syntax in other options
let heights = (4, 2, 0, 3, 2, 5); uses parentheses which is invalid for arrays. var heights = {4, 2, 0, 3, 2, 5}; uses curly braces which define objects, not arrays. const heights = 4, 2, 0, 3, 2, 5; lacks brackets and is invalid.Final Answer:
const heights = [4, 2, 0, 3, 2, 5]; -> Option AQuick Check:
Array syntax = [] [OK]
- Using parentheses () instead of brackets [] for arrays
- Using curly braces {} which create objects, not arrays
- Missing brackets leading to syntax errors
function trap(height) {
let left = 0, right = height.length - 1;
let leftMax = 0, rightMax = 0;
let water = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) leftMax = height[left];
else water += leftMax - height[left];
left++;
} else {
if (height[right] >= rightMax) rightMax = height[right];
else water += rightMax - height[right];
right--;
}
}
return water;
}
console.log(trap([4,2,0,3,2,5]));Solution
Step 1: Understand two-pointer approach
The code uses two pointers from left and right, tracking max heights and adding trapped water where current height is less than max.Step 2: Dry run with input [4,2,0,3,2,5]
Water trapped is calculated as 2 (at index 1), 4 (at index 2), 1 (at index 3), 2 (at index 4), totaling 9 units.Final Answer:
9 -> Option AQuick Check:
Two-pointer trap water = 9 [OK]
- Adding heights instead of differences
- Not updating max heights correctly
- Mixing left and right pointer logic
function trap(height) {
let left = 0, right = height.length - 1;
let leftMax = 0, rightMax = 0;
let water = 0;
while (left <= right) {
if (height[left] < height[right]) {
if (height[left] > leftMax) leftMax = height[left];
else water += leftMax - height[left];
left++;
} else {
if (height[right] > rightMax) rightMax = height[right];
else water += rightMax - height[right];
right--;
}
}
return water;
}Solution
Step 1: Analyze loop condition impact
The loop uses 'left <= right' which causes the pointers to cross and may double count or cause incorrect water calculation.Step 2: Correct loop condition
Changing the condition to 'left < right' ensures pointers stop before crossing, preventing errors in trapped water calculation.Final Answer:
The loop condition should be 'left < right' instead of 'left <= right' -> Option DQuick Check:
Loop condition fix = 'left < right' [OK]
- Using <= causes double counting or invalid access
- Changing comparison operators unnecessarily
- Not moving pointers causing infinite loops
[0,1,0,2,1,0,1,3,2,1,2,1], what is the total trapped rain water using the optimal two-pointer approach?Solution
Step 1: Apply two-pointer method on given array
Initialize left=0, right=11, leftMax=0, rightMax=0, water=0. Move pointers inward, updating max heights and adding trapped water where current height is less than max.Step 2: Calculate trapped water step-by-step
Water trapped at positions: 1 unit at index 2, 1 at index 4, 2 at index 5, 1 at index 6, 1 at index 9; total = 6 units.Final Answer:
8 -> Option CQuick Check:
Two-pointer trap water = 8 [OK]
- Forgetting to update max heights correctly
- Adding heights instead of differences
- Stopping pointers too early or too late
Ready to prove it?
Pass the test and this pattern moves unknown
