Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate factorial using recursion.
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.
Using n directly causes infinite recursion.
✗ Incorrect
The recursive call must reduce the problem size by 1 each time, so n - 1 is correct.
2fill in blank
mediumComplete the code to calculate factorial using iteration.
DSA Typescript
function factorialIter(n: number): number {
let result = 1;
for (let i = 1; i <= [1]; i++) {
result *= i;
}
return result;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using n - 1 excludes n from multiplication.
Using i or result in the condition causes errors.
✗ Incorrect
The loop runs from 1 up to n, so the condition should be i <= n.
3fill in blank
hardFix the error in the recursive Fibonacci function to avoid infinite recursion.
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 directly causes infinite recursion.
✗ Incorrect
The Fibonacci function calls fib(n-1) and fib(n-2) to reduce problem size correctly.
4fill in blank
hardFill both blanks to create a recursive function that sums numbers from n down to 1.
DSA Typescript
function sumToN(n: number): number {
if (n === 0) {
return 0;
}
return n [1] sumToN([2]);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition causes wrong results.
Using n + 1 causes infinite recursion.
✗ Incorrect
To sum numbers from n down to 1, add n to sumToN(n - 1).
5fill in blank
hardFill all three blanks to create an iterative function that reverses a string.
DSA Typescript
function reverseString(str: string): string {
let reversed = '';
for (let i = [1]; i [2] -1; i[3]) {
reversed += str[i];
}
return reversed;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting from 0 and incrementing causes no reversal.
Using '<' instead of '>' causes empty result.
✗ Incorrect
The loop starts from the last index (length - 1), continues while i > -1, and decrements i each time.