Unique Paths

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Unique Paths

Problem Link : https://leetcode.com/problems/unique-paths/

Problem Description :
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

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

Possibilities:

Here , we have two possibilities to reach the bottom right corner i.e Down and Right.

If we move right from (r,c) , our cell goes to (r , c+1)

If we move down from (r,c) , our cell goes to (r+1,c)

Step 1:
We have to write down our indexes to the matrix first. we have to move from (0,0) to
(m-1,n-1).

Suppose , we are at (0,0) and given 3 * 3 matrix ,we have 2 possibilities i.e we can go
right or down.

If we go right , we will reach(0,1) and if we go down , we reach (1,0)

Again from (0,1) , if we have 2 possibilities and they will be :

If we go right we reach (0,2) and if we go down , we reach (1,1)

Again from (0,2) , if we have 2 possibilities and they will be :

If we go right we reach (0,3) and if we go down , we reach (1,2)

Here , we reached the 3rd index which is not present in our matrix , hence we return 0.

Again from (1,2) , if we have 2 possibilities and they will be :

If we go right we reach (1,3) and if we go down , we reach (1,2)

Again we reached the third index . So, again we will return 0 and (1, 2) returns 1.

Here we perform addition of two branches as we are finding paths .

In the same way , complete the recursive tree.

Base case :

If we go out of our matrix , then we need to return 0 .

If we reach the last cell of the matrix ,i.e (m-1,n-1) we return 1 as we found a valid path.

The code for the following recursive approach looks like this:
Step 2:
Now , we have to memoize our recursive solution.

If we draw the recursion tree, we will see that there are overlapping subproblems.
Instead of computing the same value again and again, we store the values which are
changing in our memo. Hence,whenever we reach the cell which we already did,there is
no need to compute further.

Hence , the memoized solution looks like this :


Time Complexity : Here , We have 2 possibilities for each cell . Hence , The
number of cells are m * n .So, the time complexity will be O(2 power (m*n))

Space complexity : O(N)

You might also like