Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return 1 when n is 0 in the factorial function.
DSA Go
func factorial(n int) int {
if n == 0 {
return [1]
}
return n * factorial(n-1)
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning 0 instead of 1 for the base case.
Returning n which causes infinite recursion.
✗ Incorrect
The factorial of 0 is defined as 1, so the function should return 1 when n is 0.
2fill in blank
mediumComplete the recursive call to calculate factorial of n-1.
DSA Go
func factorial(n int) int {
if n == 0 {
return 1
}
return n * factorial([1])
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n+1 which causes infinite recursion.
Using n which does not reduce the problem size.
✗ Incorrect
The factorial function calls itself with n-1 to reduce the problem size until it reaches 0.
3fill in blank
hardFix the error in the base case condition to correctly identify when to stop recursion.
DSA Go
func factorial(n int) int {
if n [1] 0 {
return 1
}
return n * factorial(n-1)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using > or < which causes incorrect base case.
Using != which never stops recursion properly.
✗ Incorrect
The base case should check if n is equal to 0 to stop recursion and return 1.
4fill in blank
hardFill both blanks to complete the factorial function with correct base case and recursive call.
DSA Go
func factorial(n int) int {
if n [1] 0 {
return [2]
}
return n * factorial(n-1)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using != instead of == in base case.
Returning 0 instead of 1 in base case.
✗ Incorrect
The base case checks if n equals 0 and returns 1 to stop recursion.
5fill in blank
hardFill all three blanks to create a factorial function that handles negative input by returning 0, and calculates factorial recursively for non-negative input.
DSA Go
func factorial(n int) int {
if n [1] 0 {
return [2]
}
if n == 0 {
return 1
}
return n * factorial([3])
}Attempts:
3 left
💡 Hint
Common Mistakes
Not handling negative input causing infinite recursion.
Using == instead of < for negative check.
✗ Incorrect
If n is less than 0, factorial returns 0 (invalid input). Otherwise, it calculates factorial recursively.
