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•Math & Geometry
MediumLC 54

Spiral Matrix (LeetCode 54)

Target Frequency:GoogleMetaAmazon

You're given an m x n matrix. Read off every cell in spiral order and return that as one flat list.

Picture peeling the matrix like an onion: sweep across the still-unvisited top row heading right, then drop down the still-unvisited rightmost column, then sweep back across the still-unvisited bottom row heading left, then climb the still-unvisited leftmost column -- shrinking the unvisited region on each pass until every cell has been read.

Worked Examples

Example 1
Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output:[1,2,3,6,9,8,7,4,5]
123456789
Explanation: Top row left-to-right (1,2,3), right column top-to-bottom (6,9), bottom row right-to-left (8,7), then the lone remaining middle cell (4,5).
Example 2
Input:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output:[1,2,3,4,8,12,11,10,9,5,6,7]
123456789101112
Explanation: Top row left-to-right (1,2,3,4), right column top-to-bottom (8,12), bottom row right-to-left (11,10,9), then the remaining left column bottom-to-top (5) and the leftover middle row (6,7).

⚖️Formal Constraints & Bounds

  • m == matrix.length

  • n == matrix[i].length

  • 1 <= m, n <= 10

  • -100 <= matrix[i][j] <= 100

Deep-Dive & Conceptual Insights

Core Insight

Never track complex angles. Use 4 explicit boundary coordinates top, bottom, left, right. After sweeping along an outer edge, shrink that boundary inward (top += 1, right -= 1, bottom -= 1, left += 1) and guard horizontal/vertical sweeps with top <= bottom and left <= right.

Real-World Scenario & Production Applications

Printing a board, a seating chart or a label sheet in spiral order, starting from a corner and winding inward.

Step-by-Step Execution Trace Table

StepDirectionActive BoundaryVisited CellsAppended to ResultRemaining Matrix Bounds
1Right (→)row = top (0)(0,0), (0,1), (0,2)[1, 2, 3]top: 1, bottom: 2, left: 0, right: 2
2Down (↓)col = right (2)(1,2), (2,2)[6, 9]top: 1, bottom: 2, left: 0, right: 1
3Left (←)row = bottom (2)(2,1), (2,0)[8, 7]top: 1, bottom: 1, left: 0, right: 1
4Up (↑)col = left (0)(1,0)[4]top: 1, bottom: 1, left: 1, right: 1
5Right (→)row = top (1)(1,1)[5]top: 2, bottom: 1 (top > bottom -> Terminate)
Code Shape
Archetype Code Shape
Python
1top, bottom = 0, len(matrix) - 1
2left, right = 0, len(matrix[0]) - 1
3while top <= bottom and left <= right:
4 read the top row from left to right
5 top += 1
6 read the right column from top to bottom
7 right -= 1
8 if top <= bottom:
9 read the bottom row from right to left
10 bottom -= 1
11 if left <= right:
12 read the left column from bottom to top
13 left += 1
14return result

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Four variables (top, bottom, left, right) mutating together in a loop is easy to lose track of — but they're all doing one very physical thing.

🧅 The Analogy: Peeling an Onion, Layer by Layer

Think of the matrix as an onion made of concentric rectangular rings. The outermost ring is the top row, right column, bottom row, and left column of the whole matrix. Once you've walked all the way around that ring, it's gone — you peel it off and you're left with a smaller onion (a smaller rectangle) sitting one layer inward. You repeat the exact same "walk the ring" move on the smaller onion, and the smaller one after that, until nothing is left.

🔑 The Key Idea in the Code

top, bottom, left, right are the four walls of the current, still-unpeeled onion layer. Every full lap (right → down → left → up) peels exactly one wall inward per side, so the "onion" strictly shrinks each pass. The two guard checks (if top <= bottom, if left <= right) exist purely so a layer that's been reduced to a single remaining row or column doesn't get walked twice — once going one direction, then again coming back.

  • Traversing bottom row or left column when boundaries have crossed: After traversing right and down, top and bottom or left and right may have crossed. You must verify top <= bottom before traversing left, and left <= right before traversing up.

  • Allocating visited matrix when 4 boundaries suffice: Four bounding pointers (top, bottom, left, right) achieve O(1)O(1)O(1) auxiliary space without memory allocation.

  • Off-by-one on boundary increments: Forgetting to advance boundaries (top += 1, right -= 1, bottom -= 1, left += 1) causes infinite loops or duplicate cell outputs.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

2D matrix spiral traversal, layer-by-layer perimeter extraction, clockwise coordinate rotation.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: Traverse along the current active boundary row or column, then shrink that boundary coordinate toward the center.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • The card's trap is the thin last ring: run the debugger on a single row such as [[1,2,3]] to see the bottom guard skip the sweep.

  • Off-by-one indexing on boundary corner elements (e.g. re-visiting the top-right corner during the right-column sweep).

The 60-Second Interview Pitch

Say this out loud before you type a single line

This is Spiral Matrix: I peel the matrix layer by layer with four boundaries: top = 0, bottom = m - 1, left = 0, and right = n - 1. While top <= bottom and left <= right, I sweep right across matrix[top], down along matrix[..][right], left across matrix[bottom], and up along matrix[..][left], moving each boundary in right after its own sweep. Each boundary marks the first unread row or column on its side, so the unread cells always form a rectangle. The trap is the last thin ring: after the top and right sweeps there may be no row or column left, so I only sweep the bottom if top <= bottom and the left if left <= right; otherwise [[1,2,3]] comes back as 1, 2, 3, 2, 1. That's O(M · N) time and O(1) extra space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(M · N)

Look at the execution steps: Maintains 4 boundary pointers (top, bottom, left, right). Traverses perimeter in clockwise order, contracting boundaries inward after each row/col. Visits each of the M · N cells exactly once.

SPACE COMPLEXITY

O(1) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Output list of size M · N. Uses only 4 scalar boundary pointers in O(1) auxiliary space.

Formal Recurrence Relation

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

Derivation Progression

Clockwise Perimeter Sweep

top → right → bottom → left

Traverses outer rectangular boundary in 4 linear segments.

Boundary Contraction

top += 1, bottom -= 1, left += 1, right -= 1

Shrinks active bounding box inward after each segment in O(1).

Exact Cell Coverage

M × N cell visits

Every element in matrix is visited and extracted exactly once.

Variable Definitions

MMM

Total number of rows in the matrix

NNN

Total number of columns in the matrix

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) 4 integer registers (output array excluded)

🟢 Output Space

O(M · N) Flattened spiral array

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)

Recurrence Tree Topology

Recurrence Tree Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Phrasing triggers include "spiral order" and "all elements of the m x n matrix". The structural requirement is clockwise boundary-first peel: top row (left-to-right), right column (top-to-bottom), bottom row (right-to-left), and left column (bottom-to-top). The naive impulse is maintaining (dr,dc)(dr, dc)(dr,dc) step vectors with a boolean visited[m][n] matrix (O(MN)O(MN)O(MN) auxiliary space). An experienced engineer reaches immediately for 4-Boundary Coordinate Contraction (top, bottom, left, right) running in strictly O(1)O(1)O(1) auxiliary space.

CONSTRAINTS & BOUNDS

1≤m,n≤101 \le m, n \le 101≤m,n≤10, at most 100100100 cells. Time budget is strictly O(m×n)O(m \times n)O(m×n) to visit each cell once. Auxiliary space budget is O(1)O(1)O(1) outside the output array.

FAANG PRODUCTION TRAPS & EDGE CASES

The spiral cannot be produced in one pass over a matrix streamed row by row: the right-column sweep needs the last row before the walk turns back, so the whole matrix, or at least every row of the current ring, must be in memory.

Core Algorithmic State Invariants

  1. How Many Rings

An m x n matrix has ceil(min(m, n) / 2) rings, so the while loop runs that many times: 5 rounds for a 10 x 10 matrix, 1 round for a single row.

  1. Where the Spiral Ends

When min(m, n) is even, the last ring is at least two rows and two columns wide and both guards pass. When it is odd, the last ring is a single row, a single column or one cell, which is exactly the case the guards exist for.

Theory Context•Math & Geometry
MediumLC 54

Spiral Matrix (LeetCode 54)

Target Frequency:GoogleMetaAmazon

You're given an m x n matrix. Read off every cell in spiral order and return that as one flat list.

Picture peeling the matrix like an onion: sweep across the still-unvisited top row heading right, then drop down the still-unvisited rightmost column, then sweep back across the still-unvisited bottom row heading left, then climb the still-unvisited leftmost column -- shrinking the unvisited region on each pass until every cell has been read.

Worked Examples

Example 1
Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output:[1,2,3,6,9,8,7,4,5]
123456789
Explanation: Top row left-to-right (1,2,3), right column top-to-bottom (6,9), bottom row right-to-left (8,7), then the lone remaining middle cell (4,5).
Example 2
Input:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output:[1,2,3,4,8,12,11,10,9,5,6,7]
123456789101112
Explanation: Top row left-to-right (1,2,3,4), right column top-to-bottom (8,12), bottom row right-to-left (11,10,9), then the remaining left column bottom-to-top (5) and the leftover middle row (6,7).

⚖️Formal Constraints & Bounds

  • m == matrix.length

  • n == matrix[i].length

  • 1 <= m, n <= 10

  • -100 <= matrix[i][j] <= 100

Deep-Dive & Conceptual Insights

Core Insight

Never track complex angles. Use 4 explicit boundary coordinates top, bottom, left, right. After sweeping along an outer edge, shrink that boundary inward (top += 1, right -= 1, bottom -= 1, left += 1) and guard horizontal/vertical sweeps with top <= bottom and left <= right.

Real-World Scenario & Production Applications

Printing a board, a seating chart or a label sheet in spiral order, starting from a corner and winding inward.

Step-by-Step Execution Trace Table

StepDirectionActive BoundaryVisited CellsAppended to ResultRemaining Matrix Bounds
1Right (→)row = top (0)(0,0), (0,1), (0,2)[1, 2, 3]top: 1, bottom: 2, left: 0, right: 2
2Down (↓)col = right (2)(1,2), (2,2)[6, 9]top: 1, bottom: 2, left: 0, right: 1
3Left (←)row = bottom (2)(2,1), (2,0)[8, 7]top: 1, bottom: 1, left: 0, right: 1
4Up (↑)col = left (0)(1,0)[4]top: 1, bottom: 1, left: 1, right: 1
5Right (→)row = top (1)(1,1)[5]top: 2, bottom: 1 (top > bottom -> Terminate)
Code Shape
Archetype Code Shape
Python
1top, bottom = 0, len(matrix) - 1
2left, right = 0, len(matrix[0]) - 1
3while top <= bottom and left <= right:
4 read the top row from left to right
5 top += 1
6 read the right column from top to bottom
7 right -= 1
8 if top <= bottom:
9 read the bottom row from right to left
10 bottom -= 1
11 if left <= right:
12 read the left column from bottom to top
13 left += 1
14return result

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Four variables (top, bottom, left, right) mutating together in a loop is easy to lose track of — but they're all doing one very physical thing.

🧅 The Analogy: Peeling an Onion, Layer by Layer

Think of the matrix as an onion made of concentric rectangular rings. The outermost ring is the top row, right column, bottom row, and left column of the whole matrix. Once you've walked all the way around that ring, it's gone — you peel it off and you're left with a smaller onion (a smaller rectangle) sitting one layer inward. You repeat the exact same "walk the ring" move on the smaller onion, and the smaller one after that, until nothing is left.

🔑 The Key Idea in the Code

top, bottom, left, right are the four walls of the current, still-unpeeled onion layer. Every full lap (right → down → left → up) peels exactly one wall inward per side, so the "onion" strictly shrinks each pass. The two guard checks (if top <= bottom, if left <= right) exist purely so a layer that's been reduced to a single remaining row or column doesn't get walked twice — once going one direction, then again coming back.

  • Traversing bottom row or left column when boundaries have crossed: After traversing right and down, top and bottom or left and right may have crossed. You must verify top <= bottom before traversing left, and left <= right before traversing up.

  • Allocating visited matrix when 4 boundaries suffice: Four bounding pointers (top, bottom, left, right) achieve O(1)O(1)O(1) auxiliary space without memory allocation.

  • Off-by-one on boundary increments: Forgetting to advance boundaries (top += 1, right -= 1, bottom -= 1, left += 1) causes infinite loops or duplicate cell outputs.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

2D matrix spiral traversal, layer-by-layer perimeter extraction, clockwise coordinate rotation.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: Traverse along the current active boundary row or column, then shrink that boundary coordinate toward the center.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • The card's trap is the thin last ring: run the debugger on a single row such as [[1,2,3]] to see the bottom guard skip the sweep.

  • Off-by-one indexing on boundary corner elements (e.g. re-visiting the top-right corner during the right-column sweep).

The 60-Second Interview Pitch

Say this out loud before you type a single line

This is Spiral Matrix: I peel the matrix layer by layer with four boundaries: top = 0, bottom = m - 1, left = 0, and right = n - 1. While top <= bottom and left <= right, I sweep right across matrix[top], down along matrix[..][right], left across matrix[bottom], and up along matrix[..][left], moving each boundary in right after its own sweep. Each boundary marks the first unread row or column on its side, so the unread cells always form a rectangle. The trap is the last thin ring: after the top and right sweeps there may be no row or column left, so I only sweep the bottom if top <= bottom and the left if left <= right; otherwise [[1,2,3]] comes back as 1, 2, 3, 2, 1. That's O(M · N) time and O(1) extra space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(M · N)

Look at the execution steps: Maintains 4 boundary pointers (top, bottom, left, right). Traverses perimeter in clockwise order, contracting boundaries inward after each row/col. Visits each of the M · N cells exactly once.

SPACE COMPLEXITY

O(1) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Output list of size M · N. Uses only 4 scalar boundary pointers in O(1) auxiliary space.

Formal Recurrence Relation

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

Derivation Progression

Clockwise Perimeter Sweep

top → right → bottom → left

Traverses outer rectangular boundary in 4 linear segments.

Boundary Contraction

top += 1, bottom -= 1, left += 1, right -= 1

Shrinks active bounding box inward after each segment in O(1).

Exact Cell Coverage

M × N cell visits

Every element in matrix is visited and extracted exactly once.

Variable Definitions

MMM

Total number of rows in the matrix

NNN

Total number of columns in the matrix

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) 4 integer registers (output array excluded)

🟢 Output Space

O(M · N) Flattened spiral array

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)

Recurrence Tree Topology

Recurrence Tree Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Phrasing triggers include "spiral order" and "all elements of the m x n matrix". The structural requirement is clockwise boundary-first peel: top row (left-to-right), right column (top-to-bottom), bottom row (right-to-left), and left column (bottom-to-top). The naive impulse is maintaining (dr,dc)(dr, dc)(dr,dc) step vectors with a boolean visited[m][n] matrix (O(MN)O(MN)O(MN) auxiliary space). An experienced engineer reaches immediately for 4-Boundary Coordinate Contraction (top, bottom, left, right) running in strictly O(1)O(1)O(1) auxiliary space.

CONSTRAINTS & BOUNDS

1≤m,n≤101 \le m, n \le 101≤m,n≤10, at most 100100100 cells. Time budget is strictly O(m×n)O(m \times n)O(m×n) to visit each cell once. Auxiliary space budget is O(1)O(1)O(1) outside the output array.

FAANG PRODUCTION TRAPS & EDGE CASES

The spiral cannot be produced in one pass over a matrix streamed row by row: the right-column sweep needs the last row before the walk turns back, so the whole matrix, or at least every row of the current ring, must be in memory.

Core Algorithmic State Invariants

  1. How Many Rings

An m x n matrix has ceil(min(m, n) / 2) rings, so the while loop runs that many times: 5 rounds for a 10 x 10 matrix, 1 round for a single row.

  1. Where the Spiral Ends

When min(m, n) is even, the last ring is at least two rows and two columns wide and both guards pass. When it is odd, the last ring is a single row, a single column or one cell, which is exactly the case the guards exist for.

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