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•Graph Algorithms
MediumLC 286

Walls and Gates (LeetCode 286)

Target Frequency:AmazonMetaNetflix

You're given an m x n floor plan rooms, where every cell holds one of three values: -1 marks a wall you can't walk through, 0 marks a gate, and the sentinel INF (231 - 1, i.e. 2147483647) marks an empty room — you can assume any room that can reach a gate is always closer than that sentinel value.

Update the grid in place so every empty room instead holds the number of steps to the nearest gate, moving one cell at a time in the four compass directions. Any room a gate can never reach should keep its INF value.

Worked Examples

Example 1
Input:rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
Output:[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
2147483647-102147483647214748364721474836472147483647-12147483647-12147483647-10-121474836472147483647
Explanation: Every empty room now holds its step count to the closest gate; walls stay -1 and gates stay 0.
Example 2
Input:rooms = [[-1]]
Output:[[-1]]
-1
Explanation: The only cell is a wall, so nothing changes.

⚖️Formal Constraints & Bounds

  • m == rooms.length

  • n == rooms[i].length

  • 1 <= m, n <= 250

  • rooms[i][j] is -1, 0, or 231 - 1.

Deep-Dive & Conceptual Insights

Core Insight

Multi-source BFS ensures optimal distance assignment in a single O(R · C) pass.

Real-World Scenario & Production Applications

Emergency evacuation exit routing, fire alarm propagation modeling.

Step-by-Step Execution Trace Table

Distance WaveProcessing CellsUpdated Neighbor Rooms
0(0, 2), (3, 0)Seed initial gates
1(0, 3)=1, (1, 2)=1, (2, 0)=1Neighbors of gates
2(1, 1)=2, (2, 2)=2, (1, 0)=22 steps from gates
3(0, 0)=3, (3, 2)=33 steps from gates
4(3, 3)=4Corner reached
Trace Inputrooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
Expected[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
Distance WaveProcessing CellsUpdated Neighbor Rooms
0(0, 2), (3, 0)Seed initial gates
1(0, 3)=1, (1, 2)=1, (2, 0)=1Neighbors of gates
2(1, 1)=2, (2, 2)=2, (1, 0)=22 steps from gates
3(0, 0)=3, (3, 2)=33 steps from gates
4(3, 3)=4Corner reached
Code Shape
Archetype Code Shape
Python
1queue = deque(all_gates)
2while queue:
3 r, c = queue.popleft()
4 for each neighbor (nr, nc) in the 4 directions:
5 if (nr, nc) is inside the grid and rooms[nr][nc] == INF:
6 rooms[nr][nc] = rooms[r][c] + 1
7 queue.append((nr, nc))

Conceptual Narrative

Walls and Gates computes distance from every empty room to the nearest gate simultaneously using multi-source breadth-first search.

🧭 Conceptual Foundation & Pattern Intuition

Running individual BFS from every empty room costs O(K⋅M⋅N)O(K \cdot M \cdot N)O(K⋅M⋅N) where KKK is the number of rooms. Instead, multi-source BFS enqueues ALL gates simultaneously at distance 0 and expands outward concentrically. The first time an empty room is reached, its recorded distance is mathematically guaranteed to be the shortest.

🏟️ The Analogy: Synchronous Wildfire Expansion

Imagine lighting fires at multiple designated fire pits (gates) in a forest at the same exact second. The fire spreads 1 meter per minute in all directions. The minute fire reaches any tree is its exact distance to the nearest fire pit.

🔑 Why It Works

Overwriting empty rooms INF with dist + 1 immediately serves as the visited mark, preventing redundant enqueues.

  • Single-source BFS TLE: Running separate BFS passes from each empty room takes O(M2N2)O(M^2 N^2)O(M2N2) time; multi-source BFS from all gates simultaneously runs in O(MN)O(M N)O(MN).

  • Marking visited on pop instead of push: Waiting to mark rooms visited upon pop causes cells to be enqueued multiple times, blowing up queue memory to O(4MN)O(4^{M N})O(4MN).

  • Overwriting walls (-1) or existing gates (0): Failing to guard rooms[nr][nc] == 2147483647 overwrites obstacles and gates.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Shortest distance from multiple concurrent origins in an unweighted grid.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: first arrival at any empty room is guaranteed to be minimal distance.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Running BFS from each gate separately (O(K · R · C) vs optimal O(R · C)).

  • Mutating walls or gate cells.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I initialize a queue with all gate coordinates (r, c) where rooms[r][c] == 0. I run multi-source BFS: whenever exploring an empty room (2147483647), I update rooms[nr][nc] = rooms[r][c] + 1 and enqueue. Runs in O(R · C) time and O(R · C) queue memory."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(M · N)

Look at the execution steps: Multi-source BFS begins at all gates (0) simultaneously and updates INF rooms with their shortest distance in O(1) per room. Total M · N cell visits.

SPACE COMPLEXITY

O(M · N) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Queue holds active wavefront rooms.

Formal Recurrence Relation

T(M, N) = O(M · N)

Derivation Progression

Gate Identification

O(M · N) initial scan

Finds all 0-distance gates.

Frontier Propagation

grid[nr][nc] = grid[r][c] + 1

Sets room distance from nearest gate.

Single Update Guarantee

≤ M · N modifications

Each room is finalized on first arrival.

Variable Definitions

MMM

Total number of rows in the grid

NNN

Total number of columns in the grid

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(M · N) Queue memory

🟢 Output Space

O(1) In-place grid update

Boundary Best / Worst Cases

Best Case

O(M⋅N)O(M · N)O(M⋅N)

Average Case

O(M⋅N)O(M · N)O(M⋅N)

Worst Case

O(M⋅N)O(M · N)O(M⋅N)

Graph & Tree Traversal Frontier

Graph & Tree Traversal Frontier
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "fill each empty room with distance to nearest gate". Running independent BFS from each gate takes O(G⋅MN)=O((MN)2)O(G \cdot MN) = O((MN)^2)O(G⋅MN)=O((MN)2). A Senior SWE applies Multi-Source BFS: enqueue all gates (000) simultaneously at t=0t = 0t=0 and expand outward in concentric unit-distance rings.

CONSTRAINTS & BOUNDS

m,n≤250  ⟹  MN≈6.25×104m, n \le 250 \implies MN \approx 6.25 \times 10^4m,n≤250⟹MN≈6.25×104. Multi-source BFS visits each room at most once in O(MN)O(MN)O(MN) time (<50< 50<50ms).

FAANG PRODUCTION TRAPS & EDGE CASES

Unreachable rooms remain 214748364721474836472147483647 (INF). Obstacle walls (−1-1−1) must not be traversed.

Theory Context•Graph Algorithms
MediumLC 286

Walls and Gates (LeetCode 286)

Target Frequency:AmazonMetaNetflix

You're given an m x n floor plan rooms, where every cell holds one of three values: -1 marks a wall you can't walk through, 0 marks a gate, and the sentinel INF (231 - 1, i.e. 2147483647) marks an empty room — you can assume any room that can reach a gate is always closer than that sentinel value.

Update the grid in place so every empty room instead holds the number of steps to the nearest gate, moving one cell at a time in the four compass directions. Any room a gate can never reach should keep its INF value.

Worked Examples

Example 1
Input:rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
Output:[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
2147483647-102147483647214748364721474836472147483647-12147483647-12147483647-10-121474836472147483647
Explanation: Every empty room now holds its step count to the closest gate; walls stay -1 and gates stay 0.
Example 2
Input:rooms = [[-1]]
Output:[[-1]]
-1
Explanation: The only cell is a wall, so nothing changes.

⚖️Formal Constraints & Bounds

  • m == rooms.length

  • n == rooms[i].length

  • 1 <= m, n <= 250

  • rooms[i][j] is -1, 0, or 231 - 1.

Deep-Dive & Conceptual Insights

Core Insight

Multi-source BFS ensures optimal distance assignment in a single O(R · C) pass.

Real-World Scenario & Production Applications

Emergency evacuation exit routing, fire alarm propagation modeling.

Step-by-Step Execution Trace Table

Distance WaveProcessing CellsUpdated Neighbor Rooms
0(0, 2), (3, 0)Seed initial gates
1(0, 3)=1, (1, 2)=1, (2, 0)=1Neighbors of gates
2(1, 1)=2, (2, 2)=2, (1, 0)=22 steps from gates
3(0, 0)=3, (3, 2)=33 steps from gates
4(3, 3)=4Corner reached
Trace Inputrooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
Expected[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
Distance WaveProcessing CellsUpdated Neighbor Rooms
0(0, 2), (3, 0)Seed initial gates
1(0, 3)=1, (1, 2)=1, (2, 0)=1Neighbors of gates
2(1, 1)=2, (2, 2)=2, (1, 0)=22 steps from gates
3(0, 0)=3, (3, 2)=33 steps from gates
4(3, 3)=4Corner reached
Code Shape
Archetype Code Shape
Python
1queue = deque(all_gates)
2while queue:
3 r, c = queue.popleft()
4 for each neighbor (nr, nc) in the 4 directions:
5 if (nr, nc) is inside the grid and rooms[nr][nc] == INF:
6 rooms[nr][nc] = rooms[r][c] + 1
7 queue.append((nr, nc))

Conceptual Narrative

Walls and Gates computes distance from every empty room to the nearest gate simultaneously using multi-source breadth-first search.

🧭 Conceptual Foundation & Pattern Intuition

Running individual BFS from every empty room costs O(K⋅M⋅N)O(K \cdot M \cdot N)O(K⋅M⋅N) where KKK is the number of rooms. Instead, multi-source BFS enqueues ALL gates simultaneously at distance 0 and expands outward concentrically. The first time an empty room is reached, its recorded distance is mathematically guaranteed to be the shortest.

🏟️ The Analogy: Synchronous Wildfire Expansion

Imagine lighting fires at multiple designated fire pits (gates) in a forest at the same exact second. The fire spreads 1 meter per minute in all directions. The minute fire reaches any tree is its exact distance to the nearest fire pit.

🔑 Why It Works

Overwriting empty rooms INF with dist + 1 immediately serves as the visited mark, preventing redundant enqueues.

  • Single-source BFS TLE: Running separate BFS passes from each empty room takes O(M2N2)O(M^2 N^2)O(M2N2) time; multi-source BFS from all gates simultaneously runs in O(MN)O(M N)O(MN).

  • Marking visited on pop instead of push: Waiting to mark rooms visited upon pop causes cells to be enqueued multiple times, blowing up queue memory to O(4MN)O(4^{M N})O(4MN).

  • Overwriting walls (-1) or existing gates (0): Failing to guard rooms[nr][nc] == 2147483647 overwrites obstacles and gates.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Shortest distance from multiple concurrent origins in an unweighted grid.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: first arrival at any empty room is guaranteed to be minimal distance.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Running BFS from each gate separately (O(K · R · C) vs optimal O(R · C)).

  • Mutating walls or gate cells.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I initialize a queue with all gate coordinates (r, c) where rooms[r][c] == 0. I run multi-source BFS: whenever exploring an empty room (2147483647), I update rooms[nr][nc] = rooms[r][c] + 1 and enqueue. Runs in O(R · C) time and O(R · C) queue memory."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(M · N)

Look at the execution steps: Multi-source BFS begins at all gates (0) simultaneously and updates INF rooms with their shortest distance in O(1) per room. Total M · N cell visits.

SPACE COMPLEXITY

O(M · N) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Queue holds active wavefront rooms.

Formal Recurrence Relation

T(M, N) = O(M · N)

Derivation Progression

Gate Identification

O(M · N) initial scan

Finds all 0-distance gates.

Frontier Propagation

grid[nr][nc] = grid[r][c] + 1

Sets room distance from nearest gate.

Single Update Guarantee

≤ M · N modifications

Each room is finalized on first arrival.

Variable Definitions

MMM

Total number of rows in the grid

NNN

Total number of columns in the grid

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(M · N) Queue memory

🟢 Output Space

O(1) In-place grid update

Boundary Best / Worst Cases

Best Case

O(M⋅N)O(M · N)O(M⋅N)

Average Case

O(M⋅N)O(M · N)O(M⋅N)

Worst Case

O(M⋅N)O(M · N)O(M⋅N)

Graph & Tree Traversal Frontier

Graph & Tree Traversal Frontier
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "fill each empty room with distance to nearest gate". Running independent BFS from each gate takes O(G⋅MN)=O((MN)2)O(G \cdot MN) = O((MN)^2)O(G⋅MN)=O((MN)2). A Senior SWE applies Multi-Source BFS: enqueue all gates (000) simultaneously at t=0t = 0t=0 and expand outward in concentric unit-distance rings.

CONSTRAINTS & BOUNDS

m,n≤250  ⟹  MN≈6.25×104m, n \le 250 \implies MN \approx 6.25 \times 10^4m,n≤250⟹MN≈6.25×104. Multi-source BFS visits each room at most once in O(MN)O(MN)O(MN) time (<50< 50<50ms).

FAANG PRODUCTION TRAPS & EDGE CASES

Unreachable rooms remain 214748364721474836472147483647 (INF). Obstacle walls (−1-1−1) must not be traversed.

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