Unique Paths LeetCode Solution

Last updated on October 9th, 2024 at 10:43 pm

Here, We see Unique Paths LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Array, Dynamic Programming

Companies

Bloomberg

Level of Question

Medium

Unique Paths LeetCode Solution

Unique Paths LeetCode Solution

Problem Statement

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]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.

Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.

The test cases are generated so that the answer will be less than or equal to 2 * 109.

Example 1:

Input: m = 3, n = 7
Output: 28

Example 2:

Input: m = 3, n = 2
Output: 3
Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down

1. Unique Paths Leetcode Solution C++

class Solution {
public:
    int uniquePaths(int m, int n) {
        if(m <=0 || n <= 0) return 0;
        long long res = 1;
        for(int i = n; i < m+n-1 ; i++){
            res = res * i / (i- n + 1);
        }
        return (int)res;       
    }
};

2. Unique Paths Leetcode Solution Java

class Solution {
    public int uniquePaths(int m, int n) {
        if(m == 1 || n == 1)
            return 1;
        m--;
        n--;
        if(m < n) {
            m = m + n;
            n = m - n;
            m = m - n;
        }
        long res = 1;
        int j = 1;
        for(int i = m+1; i <= m+n; i++, j++){
            res *= i;
            res /= j;
        }  
        return (int)res;        
    }
}

3. Unique Paths Leetcode Solution JavaScript

var uniquePaths = function(m, n) {
    let perRow = Array(n).fill(1);
    let pathCount = Array.from( Array(m).fill( perRow ) );
    for(let y = 1 ; y < m ; y++){
        for(let x = 1 ; x < n ; x++){
            pathCount[y][x] = pathCount[y][x-1] + pathCount[y-1][x] 
        }
    }
    return pathCount[m-1][n-1]    
};

4. Unique Paths Leetcode Solution Python

class Solution(object):
    def uniquePaths(self, m, n):
        return math.factorial(m+n-2)/math.factorial(m-1)/math.factorial(n-1)
Scroll to Top