Unit 7 Session 1 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
HAPPY CASE
Input: 5
Output: 120
Explanation: The factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120.
EDGE CASE
Input: 0
Output: 1
Explanation: The factorial of 0 is defined as 1.
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For factorial computation problems, we can use:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use recursion to compute the factorial based on its definition.
1) Base Case: If `n` is 0, return 1 (since 0! = 1).
2) Recursive Case: Return `n * factorial(n - 1)`.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
O(n)
because we make n
recursive calls.O(n)
because each recursive call adds a layer to the call stack, using more memory.