Problem Description
Given an integer n, write a generator function that yields the factorial sequence. The factorial sequence is defined as 1, 2, 6, 24, … where each element is the factorial of its index + 1 (with the factorial of 0 defined as 1). For example, for n = 5, the sequence would yield 1, 2, 6, 24, 120.
Key Insights
- The factorial of 0 is 1.
- Use an iterative approach to compute factorials in a loop to avoid recomputation.
- Maintain a running product that is updated at each step.
- A generator function can yield each value on demand without storing the entire sequence.
Space and Time Complexity
Time Complexity: O(n) - Each factorial is computed with a single multiplication from the previous value. Space Complexity: O(1) - Only a constant amount of extra space is used regardless of n.
Solution
We use a generator function that initializes a variable for the current factorial value (starting at 1). Then, in a loop from 0 to n-1, yield the current factorial value and update it by multiplying by the next integer (i+1). This iterative approach is efficient since it increments the product at each step without recalculating previous values. The structure is simple and uses constant extra space.