Unique Paths — LeetCode 62 Python Solution
- Problem
- #62
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]).
Example
- Input
- m = 3, n = 7
- Output
- 28
Python solution
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
f = [[0] * n for _ in range(m)]
f[0][0] = 1
for i in range(m):
for j in range(n):
if i:
f[i][j] += f[i - 1][j]
if j:
f[i][j] += f[i][j - 1]
return f[-1][-1]Complexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(m \times n) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 62. Unique Paths is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
On study lists
This problem is on Blind 75, NeetCode 150, Grind 75 and LeetCode 75.
Frequently asked questions
- How hard is LeetCode 62. Unique Paths?
- LeetCode 62. Unique Paths is rated Medium on LeetCode.
- What is the time complexity of LeetCode 62. Unique Paths?
- The Python solution on this page runs in O(m \times n).
- What is the space complexity of LeetCode 62. Unique Paths?
- The Python solution on this page uses O(m \times n) auxiliary space.
- What topics does LeetCode 62. Unique Paths cover?
- LeetCode 62. Unique Paths is tagged Math, Dynamic Programming and Combinatorics on LeetCode.