Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the nth Fibonacci number using recursion.
DSA Javascript
function fib(n) {
if (n <= 1) return n;
return fib(n - 1) [1] fib(n - 2);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition in the recursive call.
Forgetting to return the sum of the two recursive calls.
✗ Incorrect
The Fibonacci number is the sum of the two previous Fibonacci numbers, so we use the + operator.
2fill in blank
mediumComplete the code to use memoization for the Fibonacci function to avoid repeated calculations.
DSA Javascript
function fibMemo(n, memo = {}) {
if (n in memo) return memo[n];
if (n <= 1) return n;
memo[n] = fibMemo(n - 1, memo) [1] fibMemo(n - 2, memo);
return memo[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Not storing the result in the memo object.
✗ Incorrect
Memoization stores results of fib(n-1) and fib(n-2) and adds them to get fib(n).
3fill in blank
hardFix the error in the code to correctly compute the minimum cost path in a grid using recursion and memoization.
DSA Javascript
function minCost(grid, i, j, memo = {}) {
const key = i + ',' + j;
if (key in memo) return memo[key];
if (i === 0 && j === 0) return grid[0][0];
if (i < 0 || j < 0) return Infinity;
const up = minCost(grid, i - 1, j, memo);
const left = minCost(grid, i, j - 1, memo);
memo[key] = Math.min(up, left) [1] grid[i][j];
return memo[key];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Not using memoization key correctly.
✗ Incorrect
The cost to reach cell (i,j) is the minimum of the cost from above or left plus the current cell's cost, so we add.
4fill in blank
hardFill both blanks to create a dictionary comprehension that maps words to their lengths only if length is greater than 3.
DSA Javascript
const words = ['tree', 'sun', 'mountain', 'sky']; const lengths = { [1]: [2] for (const word of words) if word.length > 3 };
Attempts:
3 left
💡 Hint
Common Mistakes
Using word.length() which is not a function in JavaScript.
Using word.toUpperCase() as the key or value incorrectly.
✗ Incorrect
The key is the word itself, and the value is its length using word.length property.
5fill in blank
hardFill all three blanks to create an object that maps uppercase keys to values only if the value is greater than 10.
DSA Javascript
const data = { a: 5, b: 15, c: 20 };
const filtered = { [1]: [2] for (const [k, v] of Object.entries(data)) if v [3] 10 };Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > in the condition.
Not converting keys to uppercase.
✗ Incorrect
Keys are converted to uppercase, values are kept, and only values greater than 10 are included.
