Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a recursive function that counts down from n to 1.
DSA Typescript
function countdown(n: number): void {
if (n <= 0) return;
console.log(n);
countdown([1]);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Using n does not change the argument, causing infinite recursion.
✗ Incorrect
The function calls itself with n - 1 to count down until it reaches 0.
2fill in blank
mediumComplete the code to calculate factorial of n recursively.
DSA Typescript
function factorial(n: number): number {
if (n <= 1) 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.
Returning n without recursion misses the factorial calculation.
✗ Incorrect
Factorial multiplies n by factorial of n-1 until it reaches 1.
3fill in blank
hardFix the error in the recursive Fibonacci function to correctly compute fib(n).
DSA Typescript
function fib(n: number): number {
if (n <= 1) return n;
return fib([1]) + fib(n - 2);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Using n or 1 as argument does not compute Fibonacci correctly.
✗ Incorrect
The Fibonacci number is the sum of fib(n-1) and fib(n-2).
4fill in blank
hardFill both blanks to create a recursive function that sums numbers from 1 to n.
DSA Typescript
function sumTo(n: number): number {
if (n === 1) return 1;
return n [1] sumTo(n [2] 1);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication or division instead of addition.
Not decreasing n causes infinite recursion.
✗ Incorrect
The function adds n to the sum of numbers from 1 to n-1.
5fill in blank
hardFill all three blanks to create a recursive function that reverses a string.
DSA Typescript
function reverse(str: string): string {
if (str.length <= 1) return str;
return reverse(str[1]) [2] str[3];
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect slice indices.
Using multiplication instead of concatenation.
✗ Incorrect
The function calls reverse on the string without the first character, then adds the first character at the end.