Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate Fibonacci numbers using simple recursion.
DSA Python
def fib(n): if n <= 1: return n return fib(n-1) [1] fib(n-2)
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Forgetting base cases leading to infinite recursion.
✗ Incorrect
The Fibonacci sequence is defined as fib(n) = fib(n-1) + fib(n-2). So the operator must be '+'.
2fill in blank
mediumComplete the code to store computed Fibonacci values in a cache dictionary.
DSA Python
def fib_memo(n, cache={}): if n in cache: return cache[n] if n <= 1: return n cache[n] = fib_memo(n-1, cache) [1] fib_memo(n-2, cache) return cache[n]
Attempts:
3 left
💡 Hint
Common Mistakes
Not using the cache leading to slow performance.
Using wrong operators causing incorrect results.
✗ Incorrect
Memoization stores results of fib(n-1) + fib(n-2) to avoid repeated calculations.
3fill in blank
hardFix the error in the recursive Fibonacci function that causes repeated calculations.
DSA Python
def fib(n): if n <= 1: return n return fib(n-1) [1] fib(n-2)
Attempts:
3 left
💡 Hint
Common Mistakes
Changing the operator instead of adding caching.
Ignoring the exponential time complexity of naive recursion.
✗ Incorrect
The error is not an operator but the lack of caching. The operator '+' is correct but repeated calls cause inefficiency.
4fill in blank
hardFill both blanks to create a bottom-up dynamic programming solution for Fibonacci.
DSA Python
def fib_dp(n): dp = [0, 1] + [0] * (n-1) for i in range(2, n+1): dp[i] = dp[i-1] [1] dp[i-2] return dp[[2]]
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong operators in the loop.
Returning dp at wrong index.
✗ Incorrect
The bottom-up approach sums the two previous Fibonacci numbers and returns dp[n].
5fill in blank
hardFill all three blanks to create a dictionary comprehension that caches Fibonacci values with memoization.
DSA Python
cache = {0: 0, 1: 1}
fib = lambda n: cache[n] if n in cache else cache.setdefault([1], fib([2]) [3] fib(n-2))Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong keys for cache.
Using wrong operators causing incorrect sums.
✗ Incorrect
The lambda checks cache for n, else sets cache[n] to fib(n-1) + fib(n-2).
