Unique Paths

MediumDynamic Programming · Grid DP🧩 Grid DPLeetCode #62 ↗Updated

Problem

A robot stands on the top-left cell of an m x n board and wants to reach the bottom-right cell. On every move it may step only one cell right or one cell down. Return how many different routes lead from start to finish.
Inputm = 3, n = 7Output28
Inputm = 3, n = 2Output3 (R→D→D, D→R→D, D→D→R)

1 ≤ m, n ≤ 100  ·  the answer is guaranteed to be ≤ 2 × 109

Try it yourself

Java
class Solution {
    public int uniquePaths(int m, int n) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The last move into any cell came either from the cell above or the cell to the left, so ways(r, c) = ways(r-1, c) + ways(r, c-1). Each row only needs the row above it ⇒ one 1-D array is enough.
PatternGrid DP

Instinct Grid moves that never loop back (right/down, row to row) plus "count or optimise the paths" - build dp[r][c] from the cells that can step in.

Memory hack Every cell asks its parents - a cell's answer comes only from the neighbours that can move into it, so fill cells in the order they arrive.

Open the Grid DP guide →

Approaches

Brute ForcePlain Recursion

Time O(2m+n)Space O(m + n)

Count routes on an m x n board by peeling off the first move: going down leaves an (m-1) x n board, going right leaves an m x (n-1) board. A single row or column has exactly one route.

Java
public int uniquePaths(int m, int n) {
    // A board with one row or one column has only a straight-line route
    if (m == 1 || n == 1) return 1;
    return uniquePaths(m - 1, n) + uniquePaths(m, n - 1);
}

Correct and tiny, but recomputes the same sub-boards exponentially often.

At a glance

LevelApproachTimeSpace
Brute ForcePlain RecursionO(2m+n)O(m + n)
Better2-D TabulationO(m · n)O(m · n)
OptimalRolling 1-D RowO(m · n)O(n)
Common pitfalls
  • Mixing up the base case — a 1 x n board has 1 route, not n.
  • Iterating the 1-D row right-to-left — row[c-1] would still be the old value.
  • Computing the binomial with factorials — they overflow long before the answer does.
Interview tips
  • Draw a 3 x 3 grid and fill the numbers; the Pascal-triangle shape makes the recurrence obvious.
  • Show the recursion first, point at the repeated sub-boards, then tabulate.
  • Offer the combinatorics formula as a bonus once the DP is done.
Pattern
Grid path counting → moves only right/down means each cell depends on top + left, so a row-by-row DP works.
My notes saved in this browser