Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a memo object to store results.
DSA Javascript
function fib(n, memo = [1]) { if (n <= 1) return n; if (memo[n]) return memo[n]; memo[n] = fib(n - 1, memo) + fib(n - 2, memo); return memo[n]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using an array [] instead of an object for memo.
Setting memo to null or 0 which causes errors.
✗ Incorrect
We use an empty object {} as memo to store computed Fibonacci values by their index.
2fill in blank
mediumComplete the code to check if the Fibonacci value is already computed in memo.
DSA Javascript
function fib(n, memo = {}) {
if (n <= 1) return n;
if ([1]) return memo[n];
memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
return memo[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking if memo[n] == null which misses zero values.
Checking if memo[n] === 0 which is a valid Fibonacci value.
✗ Incorrect
We check if memo[n] is not undefined to know if the value is already computed.
3fill in blank
hardFix the error in the recursive call to pass memo correctly.
DSA Javascript
function fib(n, memo = {}) {
if (n <= 1) return n;
if (memo[n] !== undefined) return memo[n];
memo[n] = fib([1], memo) + fib(n - 2, memo);
return memo[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to pass memo in the first recursive call causes errors.
Passing wrong values instead of memo.
✗ Incorrect
The first recursive call must pass memo as the second argument: fib(n - 1, memo).
4fill in blank
hardFill both blanks to create a memoized factorial function.
DSA Javascript
function factorial(n, memo = [1]) { if (n <= 1) return 1; if (memo[n]) return memo[n]; memo[n] = n * factorial([2], memo); return memo[n]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using an array [] for memo instead of an object.
Increasing n in recursive call causing infinite recursion.
✗ Incorrect
Use an empty object {} for memo and call factorial with n - 1 to reduce n.
5fill in blank
hardFill all three blanks to create a memoized function that sums numbers from 1 to n.
DSA Javascript
function sumToN(n, memo = [1]) { if (n <= 1) return n; if (memo[n] !== undefined) return memo[n]; memo[n] = n + sumToN([2], memo); return memo[[3]]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Not passing memo in recursive call.
Returning memo with wrong key.
✗ Incorrect
Use {} for memo, call sumToN with n - 1, and return memo[n].
