Skip to content
mlmentorship

Unique Paths

Count paths from the top-left to bottom-right when moves can only go right or down.

Published · 4 min read ·Core ·Mixed

30-second answer map

Visual first · depth when needed

Sweep a 3 by 3 grid row by row; each interior count is old ways[col] from above plus new ways[col-1] from the left.

Preparing the visual…

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

How practice works

ML breadth · closed-book attempt

Unique Paths

Explain the mechanism, why it works, when it fails, and one alternative.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

Count paths from the top-left to bottom-right when moves can only go right or down.

Start with the concrete trace below. It shows the state the algorithm must carry as it runs.

Problem trace

Unique Paths: Sweep a 3 by 3 grid row by row; each interior count is old ways[col] from above plus new ways[col-1] from the left.

Input and goalCount paths from the top-left to bottom-right when moves can only go right or down.
Initialize the first rowFor a 3 by 3 grid, ways = [1,1,1] because each top-row cell has exactly one all-right path from the start.
1start/current11??????
rollingRow[1,1,1]

Recognize it
Use it when movement forms an acyclic grid and every path into a cell must arrive through a small fixed set of predecessor directions such as above and left.
Keep true
During a row sweep, ways[col] before update is the count from above and ways[col-1] after update is the count from the left; their sum is the current cell count.
Reuse it
When dependencies come from the previous row and current row prefix, sweep in the direction that preserves both and compress the grid to one mutable row.
Read it this way: For a 3 by 3 grid, ways = [1,1,1] because each top-row cell has exactly one all-right path from the start. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.

Pattern: Grid DP stored as one row.

Simple idea: Every cell can be reached from above or from the left. The old value in the array is the count from above. The new value to its left is the count from the left.

def unique_paths(rows: int, cols: int) -> int:
   ways = [1] * cols
   for _ in range(1, rows):
      for col in range(1, cols):
         ways[col] += ways[col - 1]
   return ways[-1]

Cost: time and space.