Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return 1 when n is 0, the base case of recursion.
DSA Typescript
function factorial(n: number): number {
if (n === [1]) {
return 1;
}
return n * factorial(n - 1);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 instead of 0 as the base case condition.
✗ Incorrect
The base case for factorial is when n is 0, returning 1 stops recursion.
2fill in blank
mediumComplete the code to call factorial recursively with n-1.
DSA Typescript
function factorial(n: number): number {
if (n === 0) {
return 1;
}
return n * factorial([1]);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
✗ Incorrect
The recursive call reduces n by 1 each time to reach the base case.
3fill in blank
hardFix the error in the base case condition to stop infinite recursion.
DSA Typescript
function sumToN(n: number): number {
if (n [1] 0) {
return 0;
}
return n + sumToN(n - 1);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using < or > causes wrong base case detection.
✗ Incorrect
The base case should check if n equals 0 to stop recursion.
4fill in blank
hardFill both blanks to create a recursive function that counts down to zero.
DSA Typescript
function countdown(n: number): void {
if (n [1] 0) {
console.log('Done');
return;
}
console.log(n);
countdown(n [2] 1);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using < or > incorrectly in base case or recursive call.
✗ Incorrect
The base case checks if n is exactly 0, and the recursive call subtracts 1.
5fill in blank
hardFill all three blanks to create a recursive function that sums numbers from 1 to n.
DSA Typescript
function sumNumbers(n: number): number {
if (n [1] 1) {
return 1;
}
return n [2] sumNumbers(n [3] 1);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using > instead of === in base case.
Using subtraction instead of addition in return.
✗ Incorrect
The base case checks if n equals 1, then returns 1. The recursive call adds n to sumNumbers(n - 1).