A robot stands in the top-left cell of a grid with m rows and n columns. It wants to reach the bottom-right cell, and on each move it can only step one cell down or one cell to the right.
Return how many different routes the robot can take. The inputs are chosen so the answer is at most 2,000,000,000.
Example 1
Input: m = 3, n = 4 Output: 10 Why: 2 downs and 3 rights in any order: C(5, 2) = 10
2 more examples and the constraints
Example 2
Input: m = 2, n = 2 Output: 2 Why: right then down, or down then right
Example 3
Input: m = 1, n = 5 Output: 1 Why: a single row: keep going right
Constraints
- 1 ≤ m, n ≤ 100
- The answer is at most 2,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Plain recursionO(2^(m+n))
- DP tableO(m·n)
- Count with combinationsO(min(m, n))
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 17 × 17 grid | Verdict |
|---|---|---|---|
| Plain recursion | O(2^(m+n)) | Shows the recurrence; far too slow | |
| DP table | O(m·n) | Passes; the one to explain first | |
| Count with combinations | O(min(m, n)) | Best; a few multiplications |
m = rows, n = columns.
Edge cases to test
- One cell. m = 1 and n = 1: the robot is already there, which counts as 1 route.
- One row or one column. Only one route, straight across or straight down.
- Long thin grid. m = 100, n = 2 gives 100: the one right move can happen on any of the 100 rows.
- Overflow on the way. In the formula, multiply before dividing and use 64-bit numbers; the final answer still fits in 32 bits.
Common mistakes
- Using C(m + n, m) instead of C(m + n − 2, m − 1): there are m − 1 downs, not m.
- Dividing before multiplying in the formula, which loses the remainder and gives a wrong count.
- Starting the top row and left column at 0 in the table, so every cell stays 0.
How to talk through it
- 1Clarify. Only down and right moves? Any blocked cells? How big can the answer get?
- 2Give the recurrence. paths(m, n) = paths(m − 1, n) + paths(m, n − 1), with 1 for a single row or column. Point out the repeated calls.
- 3Fill the table. Each cell is above plus left; O(m·n) time, and one row of memory is enough.
- 4Offer the formula. A path is a choice of which moves are downs: C(m + n − 2, m − 1). Compute it as a running product.
- 5Test out loud. Run 1 × 1, a single row, and 2 × 2 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?