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•Dynamic Programming
MediumLC 62

Unique Paths (LeetCode 62)

Target Frequency:GoogleAppleNetflix

Picture a robot dropped onto the top-left cell of an m x n grid, aiming for the bottom-right cell. On every move it can step either one cell down or one cell right -- nothing else.

Given the grid dimensions m and n, count how many distinct routes the robot could take from start to finish. You can assume the true count never exceeds 2 * 109.

Worked Examples

Example 1
Input:m = 3, n = 7
Output:28
000000000000000000000
Explanation: A robot moving only down or right has 28 different routes across a 3 x 7 grid.
Example 2
Input:m = 3, n = 2
Output:3
Explanation: Starting from the top-left cell, exactly three distinct move sequences reach the bottom-right cell: Right, Down, Down; Down, Down, Right; and Down, Right, Down.

⚖️Formal Constraints & Bounds

  • 1 <= m, n <= 100

Deep-Dive & Conceptual Insights

Core Insight

Pascal's triangle addition achieves O(N) memory with one rolling row.

Real-World Scenario & Production Applications

Grid circuit routing paths, robotic path count enumeration.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Perimeter Boundary Constraints

Top row dp[0][j] and leftmost column dp[i][0] each have only 1 unique path (moving strictly right or strictly down).

Mathematical Recurrence / Code Invariant
# Perimeter Base Invariant
row = [1] * N  # 1 path for every cell in top row

Step-by-Step Execution Trace Table

RowColumn Values (dp array)
Row 0[1, 1, 1, 1, 1, 1, 1]
Row 1[1, 2, 3, 4, 5, 6, 7]
Row 2[1, 3, 6, 10, 15, 21, 28]
Worked on Paper

The Math, Step by Step

1. The number the table holds

Number the rows 0…m−10 \ldots m - 10…m−1 from the top and the columns 0…n−10 \ldots n - 10…n−1 from the left. Call P(r,c)P(r, c)P(r,c) the number of different routes from the start cell (0,0)(0, 0)(0,0) to cell (r,c)(r, c)(r,c), moving only down or right. The answer is P(m−1,n−1)P(m - 1, n - 1)P(m−1,n−1).

2. The value of one cell

The last move into cell (r,c)(r, c)(r,c) comes from one of two cells.

Where the robot was beforeLast moveRoutes that end this way
(r−1,c)(r - 1, c)(r−1,c), the cell abovedownP(r−1,c)P(r - 1, c)P(r−1,c)
(r,c−1)(r, c - 1)(r,c−1), the cell to the leftrightP(r,c−1)P(r, c - 1)P(r,c−1)

The two groups of routes do not overlap, because their last moves differ. Together they are all routes into (r,c)(r, c)(r,c). So

P(r,c)=P(r−1,c)+P(r,c−1)P(r, c) = P(r - 1, c) + P(r, c - 1)P(r,c)=P(r−1,c)+P(r,c−1)

The first row and the first column are the base cases. A cell in row 0 can only be reached by moving right, so P(0,c)=1P(0, c) = 1P(0,c)=1. A cell in column 0 can only be reached by moving down, so P(r,0)=1P(r, 0) = 1P(r,0)=1.

3. Why the table equals a binomial coefficient

Every route from (0,0)(0, 0)(0,0) to (m−1,n−1)(m - 1, n - 1)(m−1,n−1) makes exactly m−1m - 1m−1 down moves and n−1n - 1n−1 right moves. That is m+n−2m + n - 2m+n−2 moves in total. A route is fixed once you choose which of those moves are the down moves. The number of ways to choose m−1m - 1m−1 positions out of m+n−2m + n - 2m+n−2 is the binomial coefficient:

P(m−1,n−1)=(m+n−2m−1)P(m - 1, n - 1) = \binom{m + n - 2}{m - 1}P(m−1,n−1)=(m−1m+n−2​)

The recurrence of part 2 is the same rule that builds Pascal's triangle, (kj)=(k−1j−1)+(k−1j)\binom{k}{j} = \binom{k - 1}{j - 1} + \binom{k - 1}{j}(jk​)=(j−1k−1​)+(jk−1​). So the table the code fills is Pascal's triangle. The cells with the same value of r+cr + cr+c form one row of the triangle. The code never computes a binomial coefficient. It only adds, and the formula confirms its result.

4. One row is enough

The code keeps a single list row of length nnn instead of a full m×nm \times nm×n table. At the start, row is the first grid row, all 111.

For each next grid row, the inner loop runs row[j] += row[j - 1] for jjj from 1 to n−1n - 1n−1. Before this line, row[j] still holds the value of the cell above, P(r−1,c)P(r - 1, c)P(r−1,c). row[j - 1] was already updated in this pass, so it holds the cell to the left, P(r,c−1)P(r, c - 1)P(r,c−1). The sum is P(r,c)P(r, c)P(r,c).

row[0] is never changed, because column 0 always has 111 route. The loop must run from left to right. If it ran from right to left, row[j - 1] would still hold the row above.

5. Example 1 by hand

m = 3, n = 7. The list row after each grid row:

Grid rowrow
0 (start)[1, 1, 1, 1, 1, 1, 1]
1[1, 2, 3, 4, 5, 6, 7]
2[1, 3, 6, 10, 15, 21, 28]
1111111123456713610152128

The grid shows P(r,c)P(r, c)P(r,c) for every cell of the 3×73 \times 73×7 grid. The three marked cells show the rule of part 2 for the last cell. The cell above it holds 777, and the cell to its left holds 212121. So the bottom-right cell holds 7+21=287 + 21 = 287+21=28.

The code returns row[6] = 28, the expected output. The formula agrees: (3+7−23−1)=(82)=8⋅72=28\binom{3 + 7 - 2}{3 - 1} = \binom{8}{2} = \frac{8 \cdot 7}{2} = 28(3−13+7−2​)=(28​)=28⋅7​=28.

6. Example 2 by hand

m = 3, n = 2. The list row starts as [1, 1]. After grid row 1 it is [1, 2], and after grid row 2 it is [1, 3]. The code returns 3, the expected output. The formula agrees: (3+2−23−1)=(32)=3\binom{3 + 2 - 2}{3 - 1} = \binom{3}{2} = 3(3−13+2−2​)=(23​)=3. The three routes are Right, Down, Down; Down, Down, Right; and Down, Right, Down.

7. From the formulas to the code
FormulaIn uniquePaths
P(0,c)=1P(0, c) = 1P(0,c)=1 for the first rowrow = [1] * n
one pass per grid row 1…m−11 \ldots m - 11…m−1for _ in range(1, m):
P(r,0)=1P(r, 0) = 1P(r,0)=1row[0] is never changed, because the inner loop starts at j = 1
P(r,c)=P(r−1,c)+P(r,c−1)P(r, c) = P(r - 1, c) + P(r, c - 1)P(r,c)=P(r−1,c)+P(r,c−1)row[j] += row[j - 1]
P(m−1,n−1)P(m - 1, n - 1)P(m−1,n−1)return row[n - 1]

The two loops run (m−1)⋅(n−1)(m - 1) \cdot (n - 1)(m−1)⋅(n−1) additions, so the code takes O(m⋅n)O(m \cdot n)O(m⋅n) time. The list row takes O(n)O(n)O(n) space.

Code Shape
Archetype Code Shape
Python
1row = [1] * n
2for _ in range(1, m):
3 for j in range(1, n):
4 row[j] += row[j - 1]
5return row[n - 1]

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

In a grid of size M×NM \times NM×N, a robot starts at the top-left corner (0,0)(0, 0)(0,0) and must navigate to the bottom-right corner (M−1,N−1)(M-1, N-1)(M−1,N−1), moving only Right or Down. Every path into cell (r,c)(r, c)(r,c) must arrive from either the top neighbor (r−1,c)(r-1, c)(r−1,c) or the left neighbor (r,c−1)(r, c-1)(r,c−1). By the Addition Principle of Combinatorics, the total unique paths into (r,c)(r, c)(r,c) is dp[r][c]=dp[r−1][c]+dp[r][c−1]dp[r][c] = dp[r-1][c] + dp[r][c-1]dp[r][c]=dp[r−1][c]+dp[r][c−1]. This generates Pascal's Triangle rotated across the grid.

🏟️ The Analogy: Two One-Way Traffic Rivers Merging

Imagine water flowing through an irrigation grid. Water is only allowed to flow East or South. At any intersection (r,c)(r, c)(r,c), the water volume arriving is simply the volume coming from the North plus the volume coming from the West. Along the top canal (row 0), water only flows East (1 path). Along the left canal (column 0), water only flows South (1 path). Every interior intersection simply sums the water volumes of its two feeding tributaries.

🔑 Why It Works

The space optimization is gorgeous: instead of allocating an M×NM \times NM×N matrix, we use a single 1D array of size NNN. When computing row[j] += row[j - 1], the old value row[j] represents the cell directly above (from the previous row), while row[j - 1] is the newly updated cell to the left. The 2D matrix collapses into a 1D running accumulator!

  • Row/column boundary initialization off-by-one: Leaving outer rows/columns uninitialized. The robot can only reach any cell in the top row by moving right (1 way) and leftmost column by moving down (1 way). All boundary cells must be initialized to 1.

  • Allocating M×NM \times NM×N grid space unnecessarily: Calculating row-by-row requires only a single 1D rolling array of size NNN: dp[j] += dp[j - 1].

  • Combinatorial factorial float precision drift: Calculating (m+n−2m−1)\binom{m+n-2}{m-1}(m−1m+n−2​) using floating-point division causes precision loss on large values of m,nm, nm,n.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Counting paths in a rectangular grid moving only right and down.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: before row[j] += row[j - 1], row[j] holds the count for the cell above and row[j - 1] the count for the cell to the left, so after it row[j] is the count for the current cell.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • for j in range(1, n), not range(0, n): at j = 0 the line row[j] += row[j - 1] reads row[-1], the last cell, so the first column no longer has exactly one path.

  • Obstacle grids (Unique Paths II (LC 63)): a blocked cell must be set to 0 ways instead of summed, and a block in the first row or column cuts off every cell after it.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I'd use Grid DP. A path can only enter a cell from above or from the left, so the number of paths to a cell is the paths to the cell above plus the paths to the cell on its left. I fill the grid row by row, left to right, so both of those are final when I read them, and one rolling row is enough. When I update row[j], it still holds the cell above, and row[j - 1] already holds the cell to the left, so I add them. Every cell of the first row and the first column is reached exactly one way, so row starts as all ones and j starts at 1. That is the trap: starting j at 0 reads row[-1], the last cell, without an error, and five rows of a single column return 16 instead of 1. The answer is row[n - 1], in O(M·N) time and O(N) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(M · N)

Look at the execution steps: dp[c] = dp[c] + dp[c-1]. Fills M x N grid transitions using 1D rolling array of size N (columns) across M rows. Total M * N operations.

SPACE COMPLEXITY

O(N) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. 1D rolling array of size N.

Formal Recurrence Relation

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

Derivation Progression

Recurrence Relation

dp[r][c] = dp[r-1][c] + dp[r][c-1]

Unique paths to (r, c) equals sum of paths from top and left.

1D Space Compression

row[j] += row[j - 1]

Row-by-row updates compress space from O(M · N) to O(N).

Total Time Bound

M × N cell additions

Fills table in linear time relative to grid area.

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(N) 1D rolling array of size cols (or O(min(M, N)))

🟢 Output Space

O(1) Unique paths integer

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)

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "robot in m x n grid", "moves only down or right". 2D lattice path DP: dp[r][c]=dp[r−1][c]+dp[r][c−1]dp[r][c] = dp[r-1][c] + dp[r][c-1]dp[r][c]=dp[r−1][c]+dp[r][c−1].

CONSTRAINTS & BOUNDS

m,n≤100m, n \le 100m,n≤100. Time budget O(MN)O(MN)O(MN). Space budget: rolling 1D row array reduces memory to O(N)O(N)O(N).

FAANG PRODUCTION TRAPS & EDGE CASES

Scale: the count grows like a binomial coefficient, so on a square grid it passes the signed 32-bit limit at 18 × 18 and the signed 64-bit limit at 35 × 35 (LeetCode caps the answer at 2×1092 \times 10^92×109; Python integers never overflow, Java and C++ ones do). For many queries on the same grid, fill the table once and answer each query by lookup instead of refilling it per query.

Theory Context•Dynamic Programming
MediumLC 62

Unique Paths (LeetCode 62)

Target Frequency:GoogleAppleNetflix

Picture a robot dropped onto the top-left cell of an m x n grid, aiming for the bottom-right cell. On every move it can step either one cell down or one cell right -- nothing else.

Given the grid dimensions m and n, count how many distinct routes the robot could take from start to finish. You can assume the true count never exceeds 2 * 109.

Worked Examples

Example 1
Input:m = 3, n = 7
Output:28
000000000000000000000
Explanation: A robot moving only down or right has 28 different routes across a 3 x 7 grid.
Example 2
Input:m = 3, n = 2
Output:3
Explanation: Starting from the top-left cell, exactly three distinct move sequences reach the bottom-right cell: Right, Down, Down; Down, Down, Right; and Down, Right, Down.

⚖️Formal Constraints & Bounds

  • 1 <= m, n <= 100

Deep-Dive & Conceptual Insights

Core Insight

Pascal's triangle addition achieves O(N) memory with one rolling row.

Real-World Scenario & Production Applications

Grid circuit routing paths, robotic path count enumeration.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Perimeter Boundary Constraints

Top row dp[0][j] and leftmost column dp[i][0] each have only 1 unique path (moving strictly right or strictly down).

Mathematical Recurrence / Code Invariant
# Perimeter Base Invariant
row = [1] * N  # 1 path for every cell in top row

Step-by-Step Execution Trace Table

RowColumn Values (dp array)
Row 0[1, 1, 1, 1, 1, 1, 1]
Row 1[1, 2, 3, 4, 5, 6, 7]
Row 2[1, 3, 6, 10, 15, 21, 28]
Worked on Paper

The Math, Step by Step

1. The number the table holds

Number the rows 0…m−10 \ldots m - 10…m−1 from the top and the columns 0…n−10 \ldots n - 10…n−1 from the left. Call P(r,c)P(r, c)P(r,c) the number of different routes from the start cell (0,0)(0, 0)(0,0) to cell (r,c)(r, c)(r,c), moving only down or right. The answer is P(m−1,n−1)P(m - 1, n - 1)P(m−1,n−1).

2. The value of one cell

The last move into cell (r,c)(r, c)(r,c) comes from one of two cells.

Where the robot was beforeLast moveRoutes that end this way
(r−1,c)(r - 1, c)(r−1,c), the cell abovedownP(r−1,c)P(r - 1, c)P(r−1,c)
(r,c−1)(r, c - 1)(r,c−1), the cell to the leftrightP(r,c−1)P(r, c - 1)P(r,c−1)

The two groups of routes do not overlap, because their last moves differ. Together they are all routes into (r,c)(r, c)(r,c). So

P(r,c)=P(r−1,c)+P(r,c−1)P(r, c) = P(r - 1, c) + P(r, c - 1)P(r,c)=P(r−1,c)+P(r,c−1)

The first row and the first column are the base cases. A cell in row 0 can only be reached by moving right, so P(0,c)=1P(0, c) = 1P(0,c)=1. A cell in column 0 can only be reached by moving down, so P(r,0)=1P(r, 0) = 1P(r,0)=1.

3. Why the table equals a binomial coefficient

Every route from (0,0)(0, 0)(0,0) to (m−1,n−1)(m - 1, n - 1)(m−1,n−1) makes exactly m−1m - 1m−1 down moves and n−1n - 1n−1 right moves. That is m+n−2m + n - 2m+n−2 moves in total. A route is fixed once you choose which of those moves are the down moves. The number of ways to choose m−1m - 1m−1 positions out of m+n−2m + n - 2m+n−2 is the binomial coefficient:

P(m−1,n−1)=(m+n−2m−1)P(m - 1, n - 1) = \binom{m + n - 2}{m - 1}P(m−1,n−1)=(m−1m+n−2​)

The recurrence of part 2 is the same rule that builds Pascal's triangle, (kj)=(k−1j−1)+(k−1j)\binom{k}{j} = \binom{k - 1}{j - 1} + \binom{k - 1}{j}(jk​)=(j−1k−1​)+(jk−1​). So the table the code fills is Pascal's triangle. The cells with the same value of r+cr + cr+c form one row of the triangle. The code never computes a binomial coefficient. It only adds, and the formula confirms its result.

4. One row is enough

The code keeps a single list row of length nnn instead of a full m×nm \times nm×n table. At the start, row is the first grid row, all 111.

For each next grid row, the inner loop runs row[j] += row[j - 1] for jjj from 1 to n−1n - 1n−1. Before this line, row[j] still holds the value of the cell above, P(r−1,c)P(r - 1, c)P(r−1,c). row[j - 1] was already updated in this pass, so it holds the cell to the left, P(r,c−1)P(r, c - 1)P(r,c−1). The sum is P(r,c)P(r, c)P(r,c).

row[0] is never changed, because column 0 always has 111 route. The loop must run from left to right. If it ran from right to left, row[j - 1] would still hold the row above.

5. Example 1 by hand

m = 3, n = 7. The list row after each grid row:

Grid rowrow
0 (start)[1, 1, 1, 1, 1, 1, 1]
1[1, 2, 3, 4, 5, 6, 7]
2[1, 3, 6, 10, 15, 21, 28]
1111111123456713610152128

The grid shows P(r,c)P(r, c)P(r,c) for every cell of the 3×73 \times 73×7 grid. The three marked cells show the rule of part 2 for the last cell. The cell above it holds 777, and the cell to its left holds 212121. So the bottom-right cell holds 7+21=287 + 21 = 287+21=28.

The code returns row[6] = 28, the expected output. The formula agrees: (3+7−23−1)=(82)=8⋅72=28\binom{3 + 7 - 2}{3 - 1} = \binom{8}{2} = \frac{8 \cdot 7}{2} = 28(3−13+7−2​)=(28​)=28⋅7​=28.

6. Example 2 by hand

m = 3, n = 2. The list row starts as [1, 1]. After grid row 1 it is [1, 2], and after grid row 2 it is [1, 3]. The code returns 3, the expected output. The formula agrees: (3+2−23−1)=(32)=3\binom{3 + 2 - 2}{3 - 1} = \binom{3}{2} = 3(3−13+2−2​)=(23​)=3. The three routes are Right, Down, Down; Down, Down, Right; and Down, Right, Down.

7. From the formulas to the code
FormulaIn uniquePaths
P(0,c)=1P(0, c) = 1P(0,c)=1 for the first rowrow = [1] * n
one pass per grid row 1…m−11 \ldots m - 11…m−1for _ in range(1, m):
P(r,0)=1P(r, 0) = 1P(r,0)=1row[0] is never changed, because the inner loop starts at j = 1
P(r,c)=P(r−1,c)+P(r,c−1)P(r, c) = P(r - 1, c) + P(r, c - 1)P(r,c)=P(r−1,c)+P(r,c−1)row[j] += row[j - 1]
P(m−1,n−1)P(m - 1, n - 1)P(m−1,n−1)return row[n - 1]

The two loops run (m−1)⋅(n−1)(m - 1) \cdot (n - 1)(m−1)⋅(n−1) additions, so the code takes O(m⋅n)O(m \cdot n)O(m⋅n) time. The list row takes O(n)O(n)O(n) space.

Code Shape
Archetype Code Shape
Python
1row = [1] * n
2for _ in range(1, m):
3 for j in range(1, n):
4 row[j] += row[j - 1]
5return row[n - 1]

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

In a grid of size M×NM \times NM×N, a robot starts at the top-left corner (0,0)(0, 0)(0,0) and must navigate to the bottom-right corner (M−1,N−1)(M-1, N-1)(M−1,N−1), moving only Right or Down. Every path into cell (r,c)(r, c)(r,c) must arrive from either the top neighbor (r−1,c)(r-1, c)(r−1,c) or the left neighbor (r,c−1)(r, c-1)(r,c−1). By the Addition Principle of Combinatorics, the total unique paths into (r,c)(r, c)(r,c) is dp[r][c]=dp[r−1][c]+dp[r][c−1]dp[r][c] = dp[r-1][c] + dp[r][c-1]dp[r][c]=dp[r−1][c]+dp[r][c−1]. This generates Pascal's Triangle rotated across the grid.

🏟️ The Analogy: Two One-Way Traffic Rivers Merging

Imagine water flowing through an irrigation grid. Water is only allowed to flow East or South. At any intersection (r,c)(r, c)(r,c), the water volume arriving is simply the volume coming from the North plus the volume coming from the West. Along the top canal (row 0), water only flows East (1 path). Along the left canal (column 0), water only flows South (1 path). Every interior intersection simply sums the water volumes of its two feeding tributaries.

🔑 Why It Works

The space optimization is gorgeous: instead of allocating an M×NM \times NM×N matrix, we use a single 1D array of size NNN. When computing row[j] += row[j - 1], the old value row[j] represents the cell directly above (from the previous row), while row[j - 1] is the newly updated cell to the left. The 2D matrix collapses into a 1D running accumulator!

  • Row/column boundary initialization off-by-one: Leaving outer rows/columns uninitialized. The robot can only reach any cell in the top row by moving right (1 way) and leftmost column by moving down (1 way). All boundary cells must be initialized to 1.

  • Allocating M×NM \times NM×N grid space unnecessarily: Calculating row-by-row requires only a single 1D rolling array of size NNN: dp[j] += dp[j - 1].

  • Combinatorial factorial float precision drift: Calculating (m+n−2m−1)\binom{m+n-2}{m-1}(m−1m+n−2​) using floating-point division causes precision loss on large values of m,nm, nm,n.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Counting paths in a rectangular grid moving only right and down.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: before row[j] += row[j - 1], row[j] holds the count for the cell above and row[j - 1] the count for the cell to the left, so after it row[j] is the count for the current cell.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • for j in range(1, n), not range(0, n): at j = 0 the line row[j] += row[j - 1] reads row[-1], the last cell, so the first column no longer has exactly one path.

  • Obstacle grids (Unique Paths II (LC 63)): a blocked cell must be set to 0 ways instead of summed, and a block in the first row or column cuts off every cell after it.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I'd use Grid DP. A path can only enter a cell from above or from the left, so the number of paths to a cell is the paths to the cell above plus the paths to the cell on its left. I fill the grid row by row, left to right, so both of those are final when I read them, and one rolling row is enough. When I update row[j], it still holds the cell above, and row[j - 1] already holds the cell to the left, so I add them. Every cell of the first row and the first column is reached exactly one way, so row starts as all ones and j starts at 1. That is the trap: starting j at 0 reads row[-1], the last cell, without an error, and five rows of a single column return 16 instead of 1. The answer is row[n - 1], in O(M·N) time and O(N) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(M · N)

Look at the execution steps: dp[c] = dp[c] + dp[c-1]. Fills M x N grid transitions using 1D rolling array of size N (columns) across M rows. Total M * N operations.

SPACE COMPLEXITY

O(N) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. 1D rolling array of size N.

Formal Recurrence Relation

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

Derivation Progression

Recurrence Relation

dp[r][c] = dp[r-1][c] + dp[r][c-1]

Unique paths to (r, c) equals sum of paths from top and left.

1D Space Compression

row[j] += row[j - 1]

Row-by-row updates compress space from O(M · N) to O(N).

Total Time Bound

M × N cell additions

Fills table in linear time relative to grid area.

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(N) 1D rolling array of size cols (or O(min(M, N)))

🟢 Output Space

O(1) Unique paths integer

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)

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "robot in m x n grid", "moves only down or right". 2D lattice path DP: dp[r][c]=dp[r−1][c]+dp[r][c−1]dp[r][c] = dp[r-1][c] + dp[r][c-1]dp[r][c]=dp[r−1][c]+dp[r][c−1].

CONSTRAINTS & BOUNDS

m,n≤100m, n \le 100m,n≤100. Time budget O(MN)O(MN)O(MN). Space budget: rolling 1D row array reduces memory to O(N)O(N)O(N).

FAANG PRODUCTION TRAPS & EDGE CASES

Scale: the count grows like a binomial coefficient, so on a square grid it passes the signed 32-bit limit at 18 × 18 and the signed 64-bit limit at 35 × 35 (LeetCode caps the answer at 2×1092 \times 10^92×109; Python integers never overflow, Java and C++ ones do). For many queries on the same grid, fill the table once and answer each query by lookup instead of refilling it per query.

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