A robot stands on the top-left cell of an m x n grid and wants the bottom-right cell. It can only step right or down. Return how many distinct paths it can take.
Examples
Example 1:
Input: m = 3, n = 7
Output: 28
Example 2:
Input: m = 3, n = 2
Output: 3
Explanation: right-down-down, down-right-down, down-down-right.
Example 3:
Input: m = 1, n = 1
Output: 1
Example 4:
Input: m = 10, n = 10
Output: 48620
Constraints
1 <= m, n <= 100
The answer fits in a 32-bit integer.
Prerequisites
Dynamic programming — being able to say, in one sentence, what a single cell of your table MEANS. Everything else follows from that sentence. Rolling variables: when a state only looks back one or two steps, the table collapses to a couple of numbers.
How to think about it
1. Above Plus Left, a Cell at a Time Optimal
Intuition
Count the paths instead of drawing them, a cell at a time. Every path into a cell ends with a last step, and that step comes from the cell above it or from the cell to its left, never both. So the paths to a cell are the paths to the cell above plus the paths to the cell on its left, and no path is counted twice. The top row has nothing above it and the left column nothing to its left, so each of their cells has a single path, straight along the edge. Fill a table of counts row by row, each row from left to right, so the two counts a cell needs are always there before it; the answer waits in the bottom-right corner. Returning m times n is the trap: on a 3 by 4 grid that says 12, which counts the cells, and the paths are 10. A cell's path count is the count above it plus the count to its left.
Algorithm
1. Make a table of path counts, a slot for every cell, all starting at 0. 2. Go through the grid row by row, and each row from left to right. 3. A cell in the top row or the left column gets 1. 4. Every other cell gets the count above it plus the count to its left. 5. Return the count in the bottom-right cell.
Time & Space
Time O(m*n): each cell is filled once, with a single addition. Space O(m*n): the table stores every count. One row is enough, O(n): a slot still holds the count from above, and the slot just written beside it holds the count from the left.
2. Sum of the Two Ways In Optimal
Intuition
A cell is only reachable from above or from the left, so its path count is the sum of those two. The top row and left column have exactly one route each, which seeds everything. One row of counts, updated left to right, is enough — the value already in the array is "from above" and the value just written is "from the left".
Algorithm
1. Start a row of n ones: the first row's counts. 2. For each remaining row, walk left to right adding the value to the left. 3. The last cell holds the answer.
Time & Space
Time O(m*n). Space O(n). The closed form C(m+n-2, m-1) is worth mentioning; the DP is what the interview wants built.