Unique Paths (LeetCode 62): Solution and Explanation
A robot starts in the top-left cell of an m by n grid and can only move right or down. Count how many distinct paths take it to the bottom-right cell.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force is a recursive walk: from each cell, try moving right and try moving down, and count every route that lands on the target. Each path has m + n - 2 moves, so the recursion tree has an exponential number of leaves, and most subtrees are explored many times because many different routes pass through the same cell.
The observation that collapses the work is about the last move. Any path into cell (r, c) must arrive either from the cell directly above, (r - 1, c), or from the cell directly to the left, (r, c - 1). Those two groups of paths do not overlap, so the number of ways to reach (r, c) is simply the sum of the ways to reach those two neighbors.
The edges are the base cases. Every cell in the top row can only be reached by moving right the whole way, and every cell in the left column only by moving down, so each has exactly one path. Filling the grid row by row from the top left then gives every cell's count from values already computed, and the bottom-right cell holds the answer. This is Pascal's triangle laid out on a grid, which is also why a closed-form binomial answer exists.
Approach: 2D dynamic programming table
- Create an m by n table
dpfilled with 1, which already sets the top row and left column correctly. - Loop
rfrom 1 to m - 1 and, inside it,cfrom 1 to n - 1. - Set
dp[r][c] = dp[r - 1][c] + dp[r][c - 1], combining paths arriving from above and from the left. - Because rows are filled top to bottom and columns left to right, both neighbors are always final when they are read.
- Return
dp[m - 1][n - 1].
Step-by-step example
m = 3, n = 3
- Start with every cell equal to 1: rows [1,1,1], [1,1,1], [1,1,1].
- Row 1:
dp[1][1] = dp[0][1] + dp[1][0] = 1 + 1 = 2, thendp[1][2] = dp[0][2] + dp[1][1] = 1 + 2 = 3. Row 1 is now [1,2,3]. - Row 2:
dp[2][1] = dp[1][1] + dp[2][0] = 2 + 1 = 3, thendp[2][2] = dp[1][2] + dp[2][1] = 3 + 3 = 6. Row 2 is now [1,3,6]. - Return
dp[2][2] = 6, which matches choosing 2 of the 4 moves to be down: C(4, 2) = 6.
Code: Python, Java, C++
1class Solution:
2 def uniquePaths(self, m: int, n: int) -> int:
3 dp = [[1] * n for _ in range(m)]
4
5 for r in range(1, m):
6 for c in range(1, n):
7 dp[r][c] = dp[r - 1][c] + dp[r][c - 1]
8
9 return dp[m - 1][n - 1]1class Solution {
2 public int uniquePaths(int m, int n) {
3 int[][] dp = new int[m][n];
4 for (int[] row : dp) Arrays.fill(row, 1);
5
6 for (int r = 1; r < m; r++) {
7 for (int c = 1; c < n; c++) {
8 dp[r][c] = dp[r - 1][c] + dp[r][c - 1];
9 }
10 }
11 return dp[m - 1][n - 1];
12 }
13}1class Solution {
2public:
3 int uniquePaths(int m, int n) {
4 vector<vector<int>> dp(m, vector<int>(n, 1));
5
6 for (int r = 1; r < m; r++) {
7 for (int c = 1; c < n; c++) {
8 dp[r][c] = dp[r - 1][c] + dp[r][c - 1];
9 }
10 }
11 return dp[m - 1][n - 1];
12 }
13};Time and space complexity
O(m × n)
Each of the roughly m × n cells is filled once with a single addition.
O(m × n)
The full table is stored. Since each row only needs the row above it, a single row of length n is enough if you want O(n) space.
Other approaches
Single-row DP (time O(m × n), space O(n))
Keep one array row of length n set to 1 and, for each new row, update row[c] += row[c - 1] left to right. The old value of row[c] is the cell above and row[c - 1] is the cell to the left. Same time, far less memory.
Combinatorics (time O(min(m, n)), space O(1))
Every path is a sequence of m - 1 down moves and n - 1 right moves, so the count is the binomial coefficient C(m + n - 2, m - 1). Compute it with a running product to avoid huge factorials. This is fastest but does not extend to grids with obstacles.
Common mistakes
- Starting the loops at 0 instead of 1, which reads
dp[-1]. In Python that silently wraps to the last row or column and produces wrong counts. - Initializing the table with 0 and forgetting to set the first row and column to 1, which makes every result 0.
- Computing the binomial with full factorials in Java or C++, which overflows long before the answer does. Multiply and divide incrementally instead.
- Mixing up m and n when building the table. The reference creates m rows of n columns and returns
dp[m - 1][n - 1].
Frequently asked questions
Why is the number of unique paths the sum of the top and left cells?
The robot can only move right or down, so its final move into any cell comes either from above or from the left. Those two sets of paths are disjoint and together cover every possibility, so their counts add.
What is the formula for unique paths?
The answer is C(m + n - 2, m - 1). Every path has m + n - 2 moves, and choosing which of them are down moves determines the path completely.
Can unique paths be solved in O(n) space?
Yes. Keep only one row and update it in place from left to right. Each entry before the update holds the value from the row above, and its left neighbor already holds the current row's value.
How does the problem change with obstacles?
Cells with an obstacle get a count of 0, and the first row and column stop being all ones once an obstacle blocks them. The same recurrence still works, but the combinatorics formula no longer applies.