Distinct Paths in GridLoading saved progress…

Distinct Paths in Grid

A robot sits in the top-left cell of an m × n grid. It wants to reach the bottom-right cell, and it can only ever step one cell right or one cell down — never up, left, or diagonally. Your job is to count how many distinct routes it can take. This is the classic Unique Paths lattice-path problem.

Signature

// m = number of rows, n = number of columns. Both are >= 1.
// Returns the count of distinct right/down paths from top-left to bottom-right.
function gridDistinctPaths(m: number, n: number): number;

Examples

gridDistinctPaths(3, 7); // 28
// A 3-row, 7-column grid has 28 distinct right/down routes.

gridDistinctPaths(3, 2); // 3
// Down-Down-Right, Down-Right-Down, Right-Down-Down.
gridDistinctPaths(1, 5); // 1  — only one row: go right every time
gridDistinctPaths(2, 2); // 2  — Right-Down or Down-Right

Notes

  • Only right and down. The robot never moves up or left, so no path can revisit a cell, and every path has exactly (m - 1) + (n - 1) steps.
  • A single row or column has exactly one path. When m === 1 or n === 1 there is no choice to make — the robot walks straight to the corner. gridDistinctPaths(1, n) and gridDistinctPaths(m, 1) both return 1.
  • Dimensions are at least 1. You don't need to handle 0 or negative inputs.
  • You return a count, not the paths themselves. A single non-negative integer is the answer; you never build the routes.
  • Stay within the grid. The robot can't step off the edge, which is exactly why cells on the top row and left column are reachable only one way.
Loading editor…