MediumNo. 0062

Unique Paths — LeetCode 62 Python Solution

Topics
Math, Dynamic Programming, Combinatorics
Reading time
2 min

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

PythonSolution
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

Time
O(m × n)
Space · auxiliary
O(m × n)

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

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 × n).

What is the space complexity of LeetCode 62. Unique Paths?

The Python solution on this page uses O(m × n) auxiliary space.

What topics does LeetCode 62. Unique Paths cover?

LeetCode 62. Unique Paths is tagged Math, Dynamic Programming and Combinatorics on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.