0
0
DSA Typescriptprogramming~20 mins

Recursion Base Case and Recursive Case in DSA Typescript - Practice Problems & Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Recursion Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of Recursive Factorial Function
What is the output of this TypeScript code when calling factorial(4)?
DSA Typescript
function factorial(n: number): number {
  if (n === 0) {
    return 1;
  } else {
    return n * factorial(n - 1);
  }
}
console.log(factorial(4));
A120
B10
C24
DError: Maximum call stack size exceeded
Attempts:
2 left
💡 Hint
Remember factorial of 0 is 1, and factorial(n) = n * factorial(n-1).
Predict Output
intermediate
2:00remaining
Output of Recursive Sum Function
What is printed when this code runs: sumTo(5)?
DSA Typescript
function sumTo(n: number): number {
  if (n === 1) {
    return 1;
  } else {
    return n + sumTo(n - 1);
  }
}
console.log(sumTo(5));
AError: Maximum call stack size exceeded
B10
C5
D15
Attempts:
2 left
💡 Hint
Sum from 1 to n is n*(n+1)/2.
Predict Output
advanced
2:00remaining
Output of Recursive Fibonacci Function
What is the output of console.log(fibonacci(6)) for this code?
DSA Typescript
function fibonacci(n: number): number {
  if (n <= 1) {
    return n;
  } else {
    return fibonacci(n - 1) + fibonacci(n - 2);
  }
}
console.log(fibonacci(6));
A13
BError: Maximum call stack size exceeded
C21
D8
Attempts:
2 left
💡 Hint
Fibonacci sequence starts 0,1,1,2,3,5,8,...
🔧 Debug
advanced
2:00remaining
Identify the Error in Recursive Function
What error will this code cause when calling countdown(3)?
DSA Typescript
function countdown(n: number): void {
  if (n === 0) {
    console.log("Done!");
  } else {
    console.log(n);
    countdown(n);
  }
}
countdown(3);
ATypeError: countdown is not a function
BInfinite recursion causing stack overflow
CSyntaxError: Missing return statement
DPrints 3, 2, 1, Done!
Attempts:
2 left
💡 Hint
Check if the recursive call changes the argument.
🧠 Conceptual
expert
2:00remaining
Understanding Base Case Importance
Why is the base case essential in a recursive function?
AIt stops the recursion to prevent infinite calls
BIt makes the function run faster by skipping steps
CIt allows the function to call itself multiple times
DIt initializes variables before recursion starts
Attempts:
2 left
💡 Hint
Think about what happens if recursion never stops.