Counts paths from a point to reach Origin : Memory Optimized
Given two integers N and M, which denotes the position of in the coordinate system, the task is to count path from this point to reach origin by taking steps either left or down.
Input: 3 6
Output: Number of Paths 84
Input: 3 3
Output: Number of Paths 20
We have already discussed this problem in this article –
Counts paths from a point to reach Origin
Approach: The idea is to use the Dynamic programming paradigm to solve this problem. In this problem, there is a restriction to move only left or down in a path, due to which for any point number of paths is equal to the sum of the number of paths for the left point and the number of paths for the right point and in this way we compute the path for every point in a bottom-up manner from (0, 0) to (N, M). The key observation in this problem to reduce the space is for computing the solution for a point say (i, j) we only need the value of (i-1, j) and (i, j-1), that is we don’t need the portion of (i-1, j-1) computed values once they are used.
Below is the implementation of the above approach:
Number of Paths 20
- Time Complexity: In the above-given approach, there are two loops of which takes O(N*M) time in the worst case. Therefore, the time complexity for this approach will be O(N*M).
- Space Complexity: In the above-given approach, there is a single array of the size maximum value of N and M. Therefore the space complexity for the above approach will be O(max(N, M))
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.