mediumDynamic ProgrammingDynamic Programming

Unique Paths

mediumTime: O(m*n)Space: O(n)

Recognize the pattern

count paths in gridcan only move right or downcombinatorial problem

Brute force idea

The naive version of Unique Paths sounds like this: Recursively try every path from top-left to bottom-right. Each cell branches into two choices, causing exponential blowup. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

Better approach

A calmer way to see Unique Paths is this: DP: dp[i][j] = dp[i-1][j] + dp[i][j-1]. Each cell's path count is the sum of paths from the cell above and the cell to the left. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Key invariant

The truth you want to protect throughout Unique Paths is this: Every path to cell (i,j) must come from either (i-1,j) or (i,j-1) — there's no other way to arrive. So the total paths to (i,j) is exactly the sum of paths to those two predecessors. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Watch out for

A common way to get lost in Unique Paths is this: Using 2D array when 1D suffices — since each row only depends on the current and previous row, you can compress to a single row updated left-to-right. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Dynamic Programming Pattern