Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if the result is already computed in the memo dictionary.
DSA Python
def fib(n, memo={}): if n <= 1: return n if n [1] memo: return memo[n] memo[n] = fib(n-1, memo) + fib(n-2, memo) return memo[n]
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' or '!=' instead of 'in' to check dictionary keys.
Checking if n is not in memo instead of in memo.
✗ Incorrect
We check if n is in memo to return the stored result and avoid recomputation.
2fill in blank
mediumComplete the code to store the computed Fibonacci value in the memo dictionary.
DSA Python
def fib(n, memo={}): if n <= 1: return n if n in memo: return memo[n] memo[n] = fib(n-1, memo) [1] fib(n-2, memo) return memo[n]
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Forgetting to add the two recursive calls.
✗ Incorrect
Fibonacci numbers are calculated by adding the two previous numbers.
3fill in blank
hardFix the error in the base case to correctly return the Fibonacci number for n=0 or n=1.
DSA Python
def fib(n, memo={}): if n [1] 1: return n if n in memo: return memo[n] memo[n] = fib(n-1, memo) + fib(n-2, memo) return memo[n]
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' which only checks for n == 1, missing n == 0.
Using '>' or '>=' which are incorrect for base case.
✗ Incorrect
The base case should cover n equal to 0 or 1, so use '<=' to include both.
4fill in blank
hardFill both blanks to complete the memoized factorial function.
DSA Python
def factorial(n, memo={}): if n == 0: return 1 if n [1] memo: return memo[n] memo[n] = n [2] factorial(n-1, memo) return memo[n]
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '*' for multiplication.
Checking if n is not in memo instead of in memo.
✗ Incorrect
Check if n is in memo to reuse result, and multiply n by factorial(n-1).
5fill in blank
hardFill all three blanks to complete the memoized function that counts ways to climb stairs.
DSA Python
def climb_stairs(n, memo={}): if n <= 1: return 1 if n [1] memo: return memo[n] memo[n] = climb_stairs(n-1, memo) [2] climb_stairs(n-2, memo) return memo[[3]]
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'not in' instead of 'in' for memo check.
Using '-' or '*' instead of '+' for adding ways.
Returning memo with wrong key.
✗ Incorrect
Check if n is in memo, add results of n-1 and n-2 steps, and return memo[n].
