Skip to content
mlmentorship

Unique Paths

Count disjoint final moves while one rolling row retains old-above and new-left values.

Published · 10 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

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

ML breadth · closed-book attempt

Unique Paths

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

Problem

Input. Positive integers rows and cols specifying the grid dimensions. Output. Return the number of distinct move sequences from the top-left cell to the bottom-right cell. Rules. Each move advances exactly one cell right or one cell down, remaining inside the grid. There are no obstacles, diagonal moves, or backward moves. Different move orders count separately. A one-cell grid has one route: take no moves. Example. A grid with 3 rows and 2 columns returns 3. Its routes are right-down-down, down-right-down, and down-down-right. A 3-by-7 grid returns 28.

08:00recommended time

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

30-second answer map

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.

Problem trace

Read above from the previous row and left from the row being updated

Worked example: the final move partitions paths by their incoming neighborIn a 3-by-3 grid, three paths arrive from above and three from the left. The disjoint final-move groups sum to six.Each route has exactly one finalincoming edgelast: from leftlast: from leftlast: fromabovelast: from leftlast: fromabovelast: fromaboveThree enter from above; three fromthe left. The groups sum to six.
Read it this way: In a 3-by-3 grid, three paths arrive from above and three from the left. The disjoint final-move groups sum to six. If the destination's upper neighbor is blocked, which final-move group disappears?
Full interview answer 10 min read

Count the routes across an obstacle-free rectangular grid when movement is restricted to right or down.

Problem

Input. Positive integers rows and cols specifying the grid dimensions.

Output. Return the number of distinct move sequences from the top-left cell to the bottom-right cell.

Rules. Each move advances exactly one cell right or one cell down, remaining inside the grid. There are no obstacles, diagonal moves, or backward moves. Different move orders count separately. A one-cell grid has one route: take no moves.

Example. A grid with 3 rows and 2 columns returns 3. Its routes are right-down-down, down-right-down, and down-down-right. A 3-by-7 grid returns 28.

Picture

Every path enters an interior cell through exactly one final direction. The two incoming groups are disjoint, so their counts add.

Each top-row and first-column cell has exactly one route.

Problem trace

Read above from the previous row and left from the row being updated

Input and goalCount paths from the top-left to bottom-right when moves can only go right or down.
Initialize the first rowEach top-row cell has one route; initialize ways to [1,1,1].
1start/current11??????
rollingRow[1,1,1]
start/current
(0, 0)
rolling row
[1,1,1]
column 0 / row 0
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.
Each top-row cell has one route; initialize ways to [1,1,1]. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is ways[column] still the value from above while ways[column-1] already belongs to the current row?
Reference drawing

Problem trace

Read above from the previous row and left from the row being updated

Worked example: the final move partitions paths by their incoming neighborIn a 3-by-3 grid, three paths arrive from above and three from the left. The disjoint final-move groups sum to six.Each route has exactly one finalincoming edgelast: from leftlast: from leftlast: fromabovelast: from leftlast: fromabovelast: fromaboveThree enter from above; three fromthe left. The groups sum to six.
Execution trace
Input and goalCount paths from the top-left to bottom-right when moves can only go right or down.
Initialize the first rowEach top-row cell has one route; initialize ways to [1,1,1].
1start/current11??????
rollingRow[1,1,1]
start/current
(0, 0)
rolling row
[1,1,1]
column 0 / row 0
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.
Each top-row cell has one route; initialize ways to [1,1,1]. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is ways[column] still the value from above while ways[column-1] already belongs to the current row?
Read it this way: In a 3-by-3 grid, three paths arrive from above and three from the left. The disjoint final-move groups sum to six. If the destination's upper neighbor is blocked, which final-move group disappears?

Code

Before each update, ways[col] still counts routes to the cell above.

ways[col - 1] already counts routes to the left cell in the current row. Sweep left to right to retain both meanings.

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]

For a three-by-three grid, completed rows are [1,1,1], [1,2,3], then [1,3,6]. The answer is six.

Reversing the sweep reuses stale left counts and returns four instead.

The reference uses additions and integer slots. Exact counts grow, so these are not fixed-bit costs.

One row or one column gives one route. Zero or negative dimensions are outside the reference contract.

Recall: Which value has already advanced in time? The left slot belongs to the current row; the current slot still belongs above.

Block Selected Cells

Choose this when: Some cells cannot be entered.

Accept a rectangular grid of obstacle flags; truthy entries are blocked. Start with one arrival at the origin, then process its flag too.

A blocked cell resets its count to zero. Otherwise, the same old-above/new-left addition applies.

def paths_with_obstacles(blocked):
   if not blocked or not blocked[0]:
      return 0
   ways = [0] * len(blocked[0])
   ways[0] = 1
   for row in blocked:
      for column, obstacle in enumerate(row):
         if obstacle:
            ways[column] = 0
         elif column:
            ways[column] += ways[column - 1]
   return ways[-1]

A three-by-three grid with its center blocked has two routes. A blocked start or destination gives zero, including a single blocked cell.

Empty grids return zero. Input rows are not modified. The algorithm uses additions and integer slots.

Keep Only a Residue

Choose this when: The output requires the count modulo a positive integer, not the exact count.

Transposing an obstacle-free rectangle preserves the count. Allocate the shorter dimension, and reduce initialization as well as every addition.

def unique_paths_mod(rows, columns, modulus):
   if modulus <= 0:
      raise ValueError("positive modulus required")
   if rows <= 0 or columns <= 0:
      return 0
   rows, columns = max(rows, columns), min(rows, columns)
   ways = [1 % modulus] * columns
   for _ in range(1, rows):
      for column in range(1, columns):
         ways[column] = (ways[column] + ways[column - 1]) % modulus
   return ways[-1]

Six routes modulo five give one. Modulus one gives zero even for a one-cell grid.

A nonpositive modulus raises ValueError. Nonpositive dimensions return zero when the modulus is valid.

The algorithm uses modular additions and residue slots. Residue arithmetic still depends on modulus bit length.

Transfer

Unrestricted four-direction movement destroys this predecessor order. Revisiting can introduce cycles and infinitely many walks, so the same recurrence no longer specifies the task.