VOOZH about

URL: https://www.geeksforgeeks.org/dsa/counts-paths-point-reach-origin/

⇱ Counts paths from a point to reach Origin - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Counts paths from a point to reach Origin

Last Updated : 23 Jul, 2025

You are standing on a point (n, m) and you want to go to origin (0, 0) by taking steps either left or down i.e. from each point you are allowed to move either in (n-1, m) or (n, m-1). Find the number of paths from point to origin.

Examples: 

Input : 3 6
Output : Number of Paths 84

Input : 3 0
Output : Number of Paths 1

👁 Image


 

👁 Image

Recommended Practice

As we are restricted to move down and left only we would run a recursive loop for each of the combinations of the 
steps that can be taken.

// Recursive function to count number of paths
countPaths(n, m)
{
 // If we reach bottom or top left, we are
 // have only one way to reach (0, 0)
 if (n==0 || m==0)
 return 1;

 // Else count sum of both ways
 return (countPaths(n-1, m) + countPaths(n, m-1));
} 

Below is the implementation of the above steps. 


Output
 Number of Paths 10

Time Complexity: O(min(m,n))

Auxiliary Space: O(min(m,n))

We can use Dynamic Programming as there are overlapping subproblems. We can draw recursion tree to see overlapping problems. For example, in case of countPaths(4, 4), we compute countPaths(3, 3) multiple times.


Output
 Number of Paths 10

Time Complexity: O(n*m)
Auxiliary Space: O(n*m)

Another Approach:

Using Pascal's Triangle Approach, we also solve the problem by calculating the value of n+mCn. It can be observed as a pattern when you increase the value of m keeping the value of n constant.
Below is the implementation of the above approach:

Implementation:


Output
Number of Paths: 10

Time Complexity : O((m+n)*n)
Auxiliary Space : O(n)

Comment
Article Tags: