v9.1.1
Menu

Unique Paths

mediumPRODynamic Programming & MathLinkedIn DSA

A robot on an m x n grid starts at top-left and can only move right or down. How many unique paths exist to the bottom-right?

Example

Input
3 7
Output
28
Reasoning
  • The input 3 7 means m=3m = 3 rows and n=7n = 7 columns. The robot goes from the top-left cell to the bottom-right cell, one step right or down at a time.
  • Any route must drop m−1=2m - 1 = 2 rows and cross n−1=6n - 1 = 6 columns, so every path is exactly 88 moves long: 22 downs and 66 rights. Two paths differ only in when the downs happen.
  • A tiny case makes this concrete: on a 3×23 \times 2 grid the routes are D D R, D R D and R D D, so there are 33.
  • For the sample, group the paths by the columns where the two downs happen. Both downs in the same column: 77 choices. Downs in two different columns: 7×62=21\frac{7 \times 6}{2} = 21 pairs. Total 7+21=287 + 21 = 28.
  • The output 28 is a single integer count. Notice that a 1×11 \times 1 grid gives 11: the robot is already at the goal, and the empty route still counts as one path.

Constraints

  • 1 <= m, n <= 100

More from LinkedIn DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.