Recursion Factorial
Recursion
๐ Problem Statement
Write a function factorial(n) that returns (n factorial). . By definition, . Input: 5 โ Output: 120. You must use recursion โ no for or while loops allowed.
๐ก Intuition
Recursion breaks a problem into smaller versions of itself. Factorial has a natural recursive definition: . The base case is . Each recursive call reduces by 1, and results multiply on the way back up the call stack.
๐ง Approach
- Base case: if , return 1.
- Recursive case: return .
- Validate: raise an error for negative numbers (factorial is undefined for ).
โก Complexity Analysis
Time
โ we make recursive calls, each doing work
Space
โ the call stack holds frames at its deepest point
โ ๏ธ Common Mistakes
- Forgetting the base case (), causing infinite recursion and a stack overflow
- Using as the base case, which makes
factorial(0)recurse infinitely - Not handling negative inputs (factorial undefined for )
- Confusing recursion depth with time complexity โ they are both here
๐ฏ Final Thoughts
Factorial is the "Hello World" of recursion. It teaches the two essential components: a base case that stops recursion, and a recursive case that reduces the problem. Watch out for Python's default recursion limit of 1000 for large .