Algorithms · Visualized
DP: Unique Paths
Dynamic Programming
Break problems into overlapping subproblems and store answers.
Counts how many distinct paths exist from the top-left to the bottom-right of a grid, moving only right or down at each step. Time: O(rows × cols) average, O(rows × cols) worst; space: O(rows × cols), reducible to O(cols) with a rolling 1D array.
Big-O: The most-asked interview category — 35 classics here.
Unique Paths
Dynamic ProgrammingCounts how many distinct paths exist from the top-left to the bottom-right of a grid, moving only right or down at each step. dp[i][j] represents the number of ways to reach cell (i,j), which is simply the sum of the ways to reach the cell above it and the cell to its left (since those are the only two ways to arrive).
How Unique Paths Works
- Initialize a DP grid the same size as the input grid. The first row and first column all get a value of 1, since there's only one way to reach any cell along the top edge (moving right) or left edge (moving down).
- For every other cell (i, j), compute dp[i][j] = dp[i-1][j] + dp[i][j-1] — the sum of arriving from above and arriving from the left.
- Fill the grid row by row (or column by column), since each cell depends on the cell above and to the left.
- Continue until the entire grid is filled.
- Return the value at the bottom-right cell — the total number of unique paths.
Unique Paths Worked Example
Input: {rows: 3, cols: 3}
Top row and left column all =1: [[1,1,1],[1,?,?],[1,?,?]]. dp[1][1]=dp[0][1]+dp[1][0]=1+1=2. dp[1][2]=dp[0][2]+dp[1][1]=1+2=3. dp[2][1]=dp[1][1]+dp[2][0]=2+1=3. dp[2][2]=dp[1][2]+dp[2][1]=3+3=6. Total unique paths: 6.
def unique_paths(m, n):
dp = [1] * n
for _ in range(1, m):
for c in range(1, n):
dp[c] += dp[c - 1]
return dp[-1]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Unique Paths Time & Space Complexity
When to Use Unique Paths
- Grid-based pathfinding and counting problems: robot movement planning, counting route options in city-block-style maps.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.