mediumDynamic ProgrammingDynamic Programming

Unique Paths

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

Signals to notice

count paths in gridcan only move right or downcombinatorial problem

Brute force first

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.

The key insight

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.

What must stay true

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.

Easy way to go wrong

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