Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamic Programming: Implementing a solution using memoization

As the question states, I am trying to solve a leetcode problem. The solutions are available online but, I want to implement my own solution. I have built my logic. Logic is totally fine. However, I am unable to optimize the code as the time limit is exceeding for the large numbers.

Here’s my code:

let count = 0;

const climbingStairs = (n, memo = [{stairs: null}]) => {

if(n === memo[n]) {
    count += memo[n].stairs;
}

if(n < 0) return;

if(n === 0) return memo[n].stairs = count++;

memo[n] = climbingStairs(n - 1, memo) + climbingStairs(n - 2, memo); 

return memo[n];
}

climbingStairs(20); //running fine on time
climbingStairs(40); //hangs as the code isn't optimized

console.log(count); //the output for the given number

The code optimization using the memoization object is not working. I have tried multiple ways but still, facing issues. Any help would be appreciated in optimizing the code. Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Actually, you do not store a value, but NaN to the array.

You need to return zero to get a numerical value for adding.

Further more, you assign in each call a new value, even if you already have this value in the array.

A good idea is to use only same types (object vs number) in the array and not mixed types, because you need a differen hndling for each type.

const climbingStairs = (n, memo = [1]) => {
    if (n < 0) return 0;
    return memo[n] ??= climbingStairs(n - 1, memo) + climbingStairs(n - 2, memo);
}

console.log(climbingStairs(5));
console.log(climbingStairs(20));
console.log(climbingStairs(40));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading