Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

13 Core Algorithmic Patterns & 225 Practice Problems

  • 1. Two Pointers (16 Paradigms, 43 Problems): Opposite ends, sorted pair sums, palindrome verification, trapping rain water, 3Sum, container with most water — includes the Sliding Window and Fast & Slow Pointers paradigms (contiguous subarray invariants, longest substrings, Floyd's cycle detection, linked list middle).
  • 2. Binary Search (9 Paradigms, 14 Problems): Monotonic predicate partitioning (feasible(x)), boundary search, rotated sorted arrays, square roots, minimum ship capacity, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 11 Problems): Counting set bits, XOR cancellation, bit reversal, bitmask pairing, maximum XOR with a bitwise trie.
  • 4. Math & Geometry (8 Paradigms, 14 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (15 Paradigms, 24 Problems): Path sums, lowest common ancestor, tree diameter, validating BSTs, tree DP (House Robber III, Binary Tree Cameras).
  • 6. Tree/Graph Breadth-First Search (5 Paradigms, 12 Problems): Level-order traversals, shortest path in unweighted graphs, zig-zag traversals, rotting oranges, word ladders.
  • 7. Graphs (12 Paradigms, 22 Problems): Topological sort, cycle detection, Dijkstra's algorithm, bipartite graph validation, network delay.
  • 8. Backtracking (6 Paradigms, 14 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens, Sudoku solver.
  • 9. Dynamic Programming (13 Paradigms, 28 Problems): Memoization vs tabulation, 0/1 knapsack, unbounded knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (9 Paradigms, 11 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (7 Paradigms, 17 Problems): Trie (prefix tree), Union-Find (Disjoint Set Union), LRU Cache, LFU Cache, range-sum queries with updates.
  • 12. Stack (5 Paradigms, 9 Problems): Next greater element, largest rectangle in histogram, remove k digits, decode string, min stack.
  • 13. Intervals & Greedy (2 Paradigms, 6 Problems): Merge intervals, interval scheduling, meeting rooms by sweep line, jump game.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Read the pattern's mental model, loop invariant and Big-O proof, compare the pattern's template with the problem's solution side by side, and use the step-by-step debugger. The solution can also be shown in C#, Java, TypeScript, C++, Go or Rust for almost every problem.
  2. Stage 2 (Active Recall): Rebuild the solution from memory in a code editor, with an invariant checklist and optional progressive hints, and check it against a judged test suite.
  3. Stage 3 (AI Interview Coach, coming soon): A mock-interview stage still in development; for now, students go straight from Stage 2 to Stage 4.
  4. Stage 4 (Solve on Your Own): Solve a new problem on your own against a 15-minute timer; your code is graded against a test suite. Python and TypeScript run in your browser and C# runs on our server (design problems grade in Python and TypeScript).

Equipped with a spaced-repetition review hub on a fixed 7-step schedule (1 day up to 90 days), a two-pane Studio workspace, and study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Coins: New accounts get 40 free coins once, the daily claim adds +20 coins once a day, and inviting a friend earns you +25 coins when they complete their first practice step. These are the only ways to earn coins.
  • AI Coach: Each AI coach question costs 1-5 coins, priced by the server according to its size.
  • BYOK (Bring Your Own Key): AI coaching is free with your own Google Gemini, OpenAI or OpenRouter API key (BYOK).
  • Extras: Coins also unlock extras for 24 hours: a Recall hint level (1 coin), a Solve solution reveal (2), a LeetCode problem card's solutions (1) and a pattern's extra canonical problems (1).
  • Payments & Refunds: Nothing on the site is sold for money: coins can only be earned, never bought. There are no subscriptions or charges, so there is nothing to refund.
  • Platform Operator: Hi👋WebEnterprise. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

Arena
238Items
Theory Context•Priority Queue / Heap
HardLC 407

Trapping Rain Water II (LeetCode 407)

Target Frequency:AmazonMicrosoftGoogle

You're given an m x n grid of integers heightMap, where each cell's value is the height of a unit column of terrain at that position. After rain falls across the whole map, work out how much water settles and stays trapped between the columns, and return that total volume.

Worked Examples

Example 1
Input:heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
Output:4
143132321324233231
Explanation: Once the rain settles, two small pockets of water form between the raised blocks, holding a combined volume of 4 units.
Example 2
Input:heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]
Output:10
3333332223321233222333333
Explanation: This grid forms a single deep basin at its center, which collects a total of 10 units of trapped water.

⚖️Formal Constraints & Bounds

  • m == heightMap.length

  • n == heightMap[i].length

  • 1 <= m, n <= 200

  • 0 <= heightMap[i][j] <= 2 * 104

Deep-Dive & Conceptual Insights

Core Insight

Always expanding from the currently lowest boundary cell (a min-heap frontier, exactly like Dijkstra's relaxation order) guarantees every cell's trapped-water contribution is finalized the instant it is popped.

Real-World Scenario & Production Applications

Flood-fill terrain modeling for civil engineering drainage simulations and multi-source shortest-path routing over weighted grids.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Seed the Min-Heap Frontier With the Border

Every border cell of the grid is an initial "wall." Push each as (height, r, c) into a min-heap and mark it visited -- this is the starting container before any water is measured.

Mathematical Recurrence / Code Invariant
visited = [[False] * cols for _ in range(rows)]
min_heap = []
for r in range(rows):
    for c in range(cols):
        if r in (0, rows - 1) or c in (0, cols - 1):
            heapq.heappush(min_heap, (heightMap[r][c], r, c))
            visited[r][c] = True

Step-by-Step Execution Trace Table

StepPopped (height, r, c)Neighbor FloodedWater AddedRunning Total
1(1, 0, 0)(1, 1) height 2max(0, 1-2)=00
2(1, 2, 3)(1, 3) height 3max(0, 1-3)=00
3(2, 1, 0)(1, 1) already visited--0
......(1, 2) height 1max(0, 3-1)=22
......(2, 2) height 3max(0, 3-3)=04
Code Shape
Archetype Code Shape
Python
1min_heap = every border cell as (height, r, c)
2mark every border cell visited
3while min_heap:
4 height, r, c = heappop(min_heap)
5 for each unvisited neighbor (nr, nc):
6 visited[nr][nc] = True
7 total_water += max(0, height - grid[nr][nc])
8 heappush(min_heap, (max(height, grid[nr][nc]), nr, nc))
9return total_water

Conceptual Narrative

Trapping Rain Water in 1D used two pointers racing inward from both ends. In 2D, there is no single "inward" direction — water can leak out through any of the four sides of an interior cell. The heap replaces the two pointers with a frontier of border cells that always expands from its currently weakest point.

🧭 Conceptual Foundation & Pattern Intuition

Imagine building a dam by starting with the outer rim of the terrain as your initial "wall." Water trapped at any interior cell cannot rise higher than the lowest point on the boundary enclosing it — exactly like a bathtub whose walls have one low spot: water spills out there first. So the algorithm always processes the lowest cell currently on the frontier, because that cell is the binding constraint for everything still unvisited next to it.

🏟️ The Analogy: Flooding a Terrain From the Outside In

Picture the entire grid as a walled city seen from above, where every border tile is part of the city wall. You flood the terrain starting from the shortest section of the wall — as if water were rising from the ocean outside and finding the weakest point in the perimeter first. Once you step over that weakest wall segment into the interior, the interior cell you land on immediately becomes part of the new wall (at whichever is taller: the old wall or the new cell), and its height determines whether the next cell inward gets flooded.

🔑 The Key Idea in the Code

The visited set plays the same role as Dijkstra's "finalized" set: once a cell is popped from the heap, its water contribution is permanently correct, because every cell still in the heap or unvisited is guaranteed to be reachable only through walls at least as tall as the one just popped.

  • Not initializing min-heap with all outer perimeter boundary cells: In 3D rain water, water spills off the 4 borders. All border cells of the M×NM \times NM×N grid must seed the initial min-heap and be marked visited.

  • Water trapped formula inversion: Water trapped at neighbor cell is max(0, current_boundary_height - cell_height). Inverting the subtraction yields negative water quantities.

  • Updating neighbor height when pushing to heap: When pushing an unvisited neighbor into the heap, its effective height is max(current_boundary_height, cell_height). Pushing raw cell_height leaks water below the true water level.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

2D grid + trap water + can leak in 4 directions + need the volume, not just max height.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: once a cell is popped from the min-heap, its trapped-water contribution is final -- every remaining cell is reachable only through walls at least as tall as the one just popped.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Forgetting to mark border cells visited before seeding the heap (double-processes corners).

  • Using the neighbor's own height instead of max(height, neighbor_height) when pushing the new wall -- this lets water "leak" through a taller neighbor incorrectly.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I seed a min-heap with every border cell as the initial wall and mark them visited. I repeatedly pop the lowest wall cell; for each unvisited neighbor, I add max(0, height - neighbor_height) to the total, mark it visited, and push it back with height max(height, neighbor_height) since the wall can only grow. This is Dijkstra's relaxation order applied to water trapping: O(mn log(mn)) time, O(mn) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(mn log(mn))

Look at the execution steps: Every one of the mn cells is pushed onto the heap exactly once and popped exactly once. Each heap operation costs O(log(mn)) since the heap can hold up to mn entries. Total: O(mn log(mn)).

SPACE COMPLEXITY

O(mn) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. The min-heap and the visited grid both scale with the number of cells, O(mn).

Formal Recurrence Relation

T(m, n) = mn · O(log(mn)) = O(mn log(mn))

Derivation Progression

Border Seeding

O(m + n) border cells pushed

Every border cell is pushed once as the initial wall in O(log(mn)) each.

Heap Frontier Expansion

mn cells × O(log(mn)) heap ops

Each interior cell is popped once and its up-to-4 neighbors examined; each unvisited neighbor is pushed once.

Total Time Complexity

O(mn log(mn))

Every cell contributes exactly one push and one pop across the whole run.

Variable Definitions

mmm

Number of rows in the height map

nnn

Number of columns in the height map

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(mn) Min-heap holds up to every cell

🟢 Output Space

O(1) Single integer total

Boundary Best / Worst Cases

Best Case

O(mnlog⁡(mn))O(mn \log(mn))O(mnlog(mn)) even on a flat grid (every cell still pushed/popped once).

Average Case

O(mnlog⁡(mn))O(mn \log(mn))O(mnlog(mn)).

Worst Case

O(mnlog⁡(mn))O(mn \log(mn))O(mnlog(mn)) on a deep single basin.

Binary Heap Priority Queue Tree

Binary Heap Priority Queue Tree
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Trigger: "trapping rain water in a 2D elevation map". In 1D, water level is bounded by the minimum of the max-left and max-right walls. In 2D, water spills out through the lowest point on the entire outer perimeter! A Senior SWE recognizes Dijkstra-Style Inward Boundary Contraction via Min-Heap: the cell with the lowest boundary elevation governs spillover for adjacent unvisited interior cells.

CONSTRAINTS & BOUNDS

m,n≤200  ⟹  MN≤4×104m, n \le 200 \implies MN \le 4 \times 10^4m,n≤200⟹MN≤4×104 cells. Time budget: O(MNlog⁡(MN))O(MN \log(MN))O(MNlog(MN)) heap operations, running well under 150ms.

FAANG PRODUCTION TRAPS & EDGE CASES

Water elevation monotonically increases: when expanding to a neighbor with lower height, water is trapped, but the neighbor's effective boundary height becomes max(current_height, neighbor_height) before pushing to the heap.

Theory Context•Priority Queue / Heap
HardLC 407

Trapping Rain Water II (LeetCode 407)

Target Frequency:AmazonMicrosoftGoogle

You're given an m x n grid of integers heightMap, where each cell's value is the height of a unit column of terrain at that position. After rain falls across the whole map, work out how much water settles and stays trapped between the columns, and return that total volume.

Worked Examples

Example 1
Input:heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
Output:4
143132321324233231
Explanation: Once the rain settles, two small pockets of water form between the raised blocks, holding a combined volume of 4 units.
Example 2
Input:heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]
Output:10
3333332223321233222333333
Explanation: This grid forms a single deep basin at its center, which collects a total of 10 units of trapped water.

⚖️Formal Constraints & Bounds

  • m == heightMap.length

  • n == heightMap[i].length

  • 1 <= m, n <= 200

  • 0 <= heightMap[i][j] <= 2 * 104

Deep-Dive & Conceptual Insights

Core Insight

Always expanding from the currently lowest boundary cell (a min-heap frontier, exactly like Dijkstra's relaxation order) guarantees every cell's trapped-water contribution is finalized the instant it is popped.

Real-World Scenario & Production Applications

Flood-fill terrain modeling for civil engineering drainage simulations and multi-source shortest-path routing over weighted grids.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Seed the Min-Heap Frontier With the Border

Every border cell of the grid is an initial "wall." Push each as (height, r, c) into a min-heap and mark it visited -- this is the starting container before any water is measured.

Mathematical Recurrence / Code Invariant
visited = [[False] * cols for _ in range(rows)]
min_heap = []
for r in range(rows):
    for c in range(cols):
        if r in (0, rows - 1) or c in (0, cols - 1):
            heapq.heappush(min_heap, (heightMap[r][c], r, c))
            visited[r][c] = True

Step-by-Step Execution Trace Table

StepPopped (height, r, c)Neighbor FloodedWater AddedRunning Total
1(1, 0, 0)(1, 1) height 2max(0, 1-2)=00
2(1, 2, 3)(1, 3) height 3max(0, 1-3)=00
3(2, 1, 0)(1, 1) already visited--0
......(1, 2) height 1max(0, 3-1)=22
......(2, 2) height 3max(0, 3-3)=04
Code Shape
Archetype Code Shape
Python
1min_heap = every border cell as (height, r, c)
2mark every border cell visited
3while min_heap:
4 height, r, c = heappop(min_heap)
5 for each unvisited neighbor (nr, nc):
6 visited[nr][nc] = True
7 total_water += max(0, height - grid[nr][nc])
8 heappush(min_heap, (max(height, grid[nr][nc]), nr, nc))
9return total_water

Conceptual Narrative

Trapping Rain Water in 1D used two pointers racing inward from both ends. In 2D, there is no single "inward" direction — water can leak out through any of the four sides of an interior cell. The heap replaces the two pointers with a frontier of border cells that always expands from its currently weakest point.

🧭 Conceptual Foundation & Pattern Intuition

Imagine building a dam by starting with the outer rim of the terrain as your initial "wall." Water trapped at any interior cell cannot rise higher than the lowest point on the boundary enclosing it — exactly like a bathtub whose walls have one low spot: water spills out there first. So the algorithm always processes the lowest cell currently on the frontier, because that cell is the binding constraint for everything still unvisited next to it.

🏟️ The Analogy: Flooding a Terrain From the Outside In

Picture the entire grid as a walled city seen from above, where every border tile is part of the city wall. You flood the terrain starting from the shortest section of the wall — as if water were rising from the ocean outside and finding the weakest point in the perimeter first. Once you step over that weakest wall segment into the interior, the interior cell you land on immediately becomes part of the new wall (at whichever is taller: the old wall or the new cell), and its height determines whether the next cell inward gets flooded.

🔑 The Key Idea in the Code

The visited set plays the same role as Dijkstra's "finalized" set: once a cell is popped from the heap, its water contribution is permanently correct, because every cell still in the heap or unvisited is guaranteed to be reachable only through walls at least as tall as the one just popped.

  • Not initializing min-heap with all outer perimeter boundary cells: In 3D rain water, water spills off the 4 borders. All border cells of the M×NM \times NM×N grid must seed the initial min-heap and be marked visited.

  • Water trapped formula inversion: Water trapped at neighbor cell is max(0, current_boundary_height - cell_height). Inverting the subtraction yields negative water quantities.

  • Updating neighbor height when pushing to heap: When pushing an unvisited neighbor into the heap, its effective height is max(current_boundary_height, cell_height). Pushing raw cell_height leaks water below the true water level.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

2D grid + trap water + can leak in 4 directions + need the volume, not just max height.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: once a cell is popped from the min-heap, its trapped-water contribution is final -- every remaining cell is reachable only through walls at least as tall as the one just popped.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Forgetting to mark border cells visited before seeding the heap (double-processes corners).

  • Using the neighbor's own height instead of max(height, neighbor_height) when pushing the new wall -- this lets water "leak" through a taller neighbor incorrectly.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I seed a min-heap with every border cell as the initial wall and mark them visited. I repeatedly pop the lowest wall cell; for each unvisited neighbor, I add max(0, height - neighbor_height) to the total, mark it visited, and push it back with height max(height, neighbor_height) since the wall can only grow. This is Dijkstra's relaxation order applied to water trapping: O(mn log(mn)) time, O(mn) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(mn log(mn))

Look at the execution steps: Every one of the mn cells is pushed onto the heap exactly once and popped exactly once. Each heap operation costs O(log(mn)) since the heap can hold up to mn entries. Total: O(mn log(mn)).

SPACE COMPLEXITY

O(mn) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. The min-heap and the visited grid both scale with the number of cells, O(mn).

Formal Recurrence Relation

T(m, n) = mn · O(log(mn)) = O(mn log(mn))

Derivation Progression

Border Seeding

O(m + n) border cells pushed

Every border cell is pushed once as the initial wall in O(log(mn)) each.

Heap Frontier Expansion

mn cells × O(log(mn)) heap ops

Each interior cell is popped once and its up-to-4 neighbors examined; each unvisited neighbor is pushed once.

Total Time Complexity

O(mn log(mn))

Every cell contributes exactly one push and one pop across the whole run.

Variable Definitions

mmm

Number of rows in the height map

nnn

Number of columns in the height map

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(mn) Min-heap holds up to every cell

🟢 Output Space

O(1) Single integer total

Boundary Best / Worst Cases

Best Case

O(mnlog⁡(mn))O(mn \log(mn))O(mnlog(mn)) even on a flat grid (every cell still pushed/popped once).

Average Case

O(mnlog⁡(mn))O(mn \log(mn))O(mnlog(mn)).

Worst Case

O(mnlog⁡(mn))O(mn \log(mn))O(mnlog(mn)) on a deep single basin.

Binary Heap Priority Queue Tree

Binary Heap Priority Queue Tree
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Trigger: "trapping rain water in a 2D elevation map". In 1D, water level is bounded by the minimum of the max-left and max-right walls. In 2D, water spills out through the lowest point on the entire outer perimeter! A Senior SWE recognizes Dijkstra-Style Inward Boundary Contraction via Min-Heap: the cell with the lowest boundary elevation governs spillover for adjacent unvisited interior cells.

CONSTRAINTS & BOUNDS

m,n≤200  ⟹  MN≤4×104m, n \le 200 \implies MN \le 4 \times 10^4m,n≤200⟹MN≤4×104 cells. Time budget: O(MNlog⁡(MN))O(MN \log(MN))O(MNlog(MN)) heap operations, running well under 150ms.

FAANG PRODUCTION TRAPS & EDGE CASES

Water elevation monotonically increases: when expanding to a neighbor with lower height, water is trapped, but the neighbor's effective boundary height becomes max(current_height, neighbor_height) before pushing to the heap.

© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•