AceYourInterviews
Checking sign-in…

136. Unique Paths

IntermediateExact monotone-grid path counting with one-row compression

Start at the upper-left cell and reach the lower-right cell by moving one cell right or one cell down at every step. Count all different legal move sequences.

Routes are distinguished by their ordered moves. Moves upward, leftward, or diagonally are not allowed, and the contract defines empty-grid behavior.

Example 1

Input

rows=3, columns=7

Output

28

Explanation: Every route has two down moves and six right moves, so choose the two down positions among eight moves.

Example 2

Input

rows=2, columns=2

Output

2

Explanation: The routes are right-then-down and down-then-right.

Example 3

Input

rows=1, columns=1

Output

1

Explanation: No move is needed; this is one complete route.

Example 4

Input

rows=0, columns=4

Output

0

Explanation: A missing grid dimension means no cell path exists.

Constraints

  • 0 <= rows, columns <= 2000
Hints
Hint 1

Classify routes by their final right/down move.

Hint 2

What are the counts on the first row and column of a positive grid?

Hint 3

Keep one row, initialized to ONE, and add old up to new left from left to right.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Two predecessor families on a square

3
3
"6"