1. Brute Force — Recompute Left & Right Max per Element
Intuition
At each bar, search all elements to the left to find the tallest left wall, and search all elements to the right to find the tallest right wall. The trapped water is min(maxLeft, maxRight) - height[i].
Algorithm
- At each bar, search all elements to the left to find the tallest left wall, and search all elements to the right to find the tallest right wall
- The trapped water is min(maxLeft, maxRight) - height[i].
Brute Force Column-by-Column Water Trapping Trace
2 of 2 questions left todayColumn 0 (Boundary): Water spills out to the left
Column 0 (Boundary): Water spills out to the left. Boundary columns cannot trap water.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution {public: int trap(vector<int>& height) { int n = height.size(); int totalWater = 0; for (int i = 0; i < n; i++) { int maxLeft = 0; for (int j = 0; j <= i; j++) { maxLeft = max(maxLeft, height[j]); } int maxRight = 0; for (int j = i; j < n; j++) { maxRight = max(maxRight, height[j]); } totalWater += min(maxLeft, maxRight) - height[i]; } return totalWater; }}; int main() { Solution sol; vector<int> height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; cout << "Input: [0,1,0,2,1,0,1,3,2,1,2,1]\n"; cout << "Brute Force Trapped Water: " << sol.trap(height) << "\n"; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force — Recompute Left & Right Max per Element. - Space complexity:
O(1)— Space complexity for Brute Force — Recompute Left & Right Max per Element.
Why Brute Force Doesn't Scale:
With N = 20,000, O(N2) requires 4 * 108 operations, exceeding standard 1-second execution limits.
Two pointers reduces 400,000,000 operations to just 20,000 operations (20,000x speedup), using zero extra memory.