Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate factorial using recursion.
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 causes infinite recursion.
Returning 0 ends recursion incorrectly.
✗ Incorrect
The factorial of n is n multiplied by factorial of n-1.
2fill in blank
mediumComplete the code to calculate factorial using iteration.
DSA Go
func factorialIter(n int) int {
result := 1
for i := 1; i <= [1]; i++ {
result *= i
}
return result
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n-1 misses the last multiplication.
Using i or result as loop limit is incorrect.
✗ Incorrect
The loop runs from 1 to n to multiply all numbers for factorial.
3fill in blank
hardFix the error in the recursive Fibonacci function by completing the blank.
DSA Go
func fib(n int) int {
if n <= 1 {
return n
}
return fib(n-1) + fib([1])
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n-1 twice causes infinite recursion.
Using n+1 causes wrong results.
✗ Incorrect
Fibonacci is 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 Go
func sumToN(n int) int {
if n == 0 {
return 0
}
return n [1] sumToN([2])
}Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication or division is incorrect here.
Not reducing n causes infinite recursion.
✗ Incorrect
The function adds n to the sum of numbers up to n-1.
5fill in blank
hardFill all three blanks to create an iterative function that reverses a string.
DSA Go
func reverse(s string) string {
result := ""
for i := len(s) - 1; i >= [1]; i[2] {
result += string(s[i])
}
return [3]
}Attempts:
3 left
💡 Hint
Common Mistakes
Using len(s) as lower bound causes no iterations.
Using ++ instead of -- causes infinite loop.
✗ Incorrect
The loop starts from the last index and goes down to 0, appending characters to result.
