Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Count unique paths in a grid

Compute the number of unique paths from top-left to bottom-right in an m x n grid moving only right or down.

Python practice10 minDynamic ProgrammingBeginnerLast updated March 29, 2026

Problem statement

Given two integers m and n representing the number of rows and columns in a grid, count how many unique paths exist to move from the top-left corner (0,0) to the bottom-right corner (m-1,n-1) if you can only move either down or right at any point. Write a function unique_paths(m, n) that returns the number of unique paths as an integer.

Task

Use combinatorics or DP to count the number of unique paths in a grid efficiently.

Examples

Small grid

Input

m = 3, n = 7

Output

28

There are C(3+7-2, 3-1) = C(8,2) = 28 distinct sequences of moves (down/right) to reach the end.

Input format

Two integers m and n (rows and columns).

Output format

An integer: number of unique paths from top-left to bottom-right.

Constraints

0 <= m, n <= 100; results may be large but fit in Python int. Aim for O(min(m,n)) or O(m*n) solutions.

Samples

Sample 1

Input

m = 1, n = 5

Output

1

Only one way when there's only one row: move right each time.