03. Unique Paths
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
The question is a simple problem of recursion/backtracking that can be optimised through Dynamic Programming using memoization and tabulation, to reduce the time complexity exponentially.
To put things into perspective, it takes about 0.0000006 seconds to finish 60 computations, but more than 360 YEARS for 2^60 computations, on most platforms.
We are given a matrix of M rows and N columns, where we have to reach the bottom-right corner (i.e the block with index [m-1][n-1]) from the top-left (i.e. the block with index [0][0]), moving only to the right or down from any given block.
Our first intuition would be to start from the first block and explore all possibilities on each iterations till we reach the destination, then repeat for every other possible combination along the way. Let's see how we do that while not aging beyond our generation.
Now that we've got a glamorous TLE error, let's try to optimise it by maintaining a M*N dp matrix that saves all computations for future reference. Every time we come across a cell whole value has already been found, we return that value without having to go down that road again.
Time Complexity: O(m*n)
Auxiliary Space Complexity: O(m*n) + O(m+n)
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.