Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the base case when n is 1 or 2.
DSA Typescript
function climbStairs(n: number): number {
if (n <= 2) return [1];
// rest of the code
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 1 for all base cases
Returning 0 which means no ways
✗ Incorrect
When n is 1 or 2, the number of ways to climb is n itself.
2fill in blank
mediumComplete the code to use recursion for climbing stairs.
DSA Typescript
function climbStairs(n: number): number {
if (n <= 2) return n;
return climbStairs(n - 1) [1] climbStairs(n - 2);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition
Forgetting to return the sum
✗ Incorrect
The total ways to climb n steps is the sum of ways to climb n-1 and n-2 steps.
3fill in blank
hardFix the error in the iterative solution to climb stairs.
DSA Typescript
function climbStairs(n: number): number {
if (n <= 2) return n;
let first = 1, second = 2;
for (let i = 3; i <= n; i++) {
let third = first [1] second;
first = second;
second = third;
}
return second;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition
Incorrect variable updates
✗ Incorrect
Each step count is the sum of the previous two counts.
4fill in blank
hardFill both blanks to create a memoized recursive solution.
DSA Typescript
function climbStairs(n: number, memo: number[] = []): number {
if (n <= 2) return n;
if (memo[n] !== undefined) return memo[n];
memo[n] = climbStairs(n [1], memo) [2] climbStairs(n - 2, memo);
return memo[n];
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 instead of n - 1
Using subtraction instead of addition to combine results
✗ Incorrect
We subtract 1 from n for the first recursive call and add the results of both calls.
5fill in blank
hardFill all three blanks to create a bottom-up dynamic programming solution.
DSA Typescript
function climbStairs(n: number): number {
if (n <= 2) return n;
const dp: number[] = [0, 1, 2];
for (let i = 3; i <= n; i++) {
dp[i] = dp[i [1]] [2] dp[i [3]];
}
return dp[n];
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of addition
Incorrect indices for dp array
✗ Incorrect
Each dp[i] is the sum of dp[i-1] and dp[i-2].