↻one more pass.
Dynamic programming · Medium

Unique Paths: the idea to remember.

Count ways to move from the top left to bottom right of an m by n grid using only right or down moves.

Solve on LeetCode ↗

The core insight

Keep one row of counts, updating each cell by adding its count from the left.

Why it works

Every incoming path comes from exactly one of the cell above and the cell to the left. The first row and column each have one path.

The mistake to avoid

Update left to right so dp[col minus one] already represents the current row.

Time: O(mn)Space: O(n)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int uniquePaths(int m, int n) {
    int[] dp = new int[n];
    Arrays.fill(dp, 1);
    for (int row = 1; row < m; row++)
        for (int col = 1; col < n; col++) dp[col] += dp[col - 1];
    return dp[n - 1];
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.