Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Big O complexity of NumberOfPathsInMxNMatrix.java #273

Open
Frantch opened this issue May 24, 2020 · 1 comment
Open

Big O complexity of NumberOfPathsInMxNMatrix.java #273

Frantch opened this issue May 24, 2020 · 1 comment

Comments

@Frantch
Copy link

Frantch commented May 24, 2020

Hello,

I'm trying to figure out the Big O complexity of both of the algorithm writtne in https://github.com/mission-peace/interview/blob/master/src/com/interview/dynamic/NumberOfPathsInMxNMatrix.java

Is it correct to say for countPaths
O(countPaths) = n + m + n*m

And what would it be for the recursive approach ?

thank you!

@WimukthiRajapaksha
Copy link

Hello @Frantch,
As you're traversing through the whole grid it's simply O(n*m) and space complexity is O(n*m). For the recursive approach, always you have to consider 2 paths to calculate and as you're not using a memoization technique, there are overlapping sub problems. So the time complexity is O(2^n).

Furthermore you can further improve the solution by reducing space complexity only to O(n) like,

public int uniquePaths(int m, int n) {
   int[] arr=new int[n];
   for(int i=0; i<m; i++) {
       for(int j=0; j<n; j++) {
           if(i==0 || j==0) {
               arr[j]=1;
               continue;
           }
           arr[j]+=arr[j-1];
       }
   }
   return arr[n-1];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants