Factorial – Solution & Complexity

Solution Walkthrough

  1. Step 1: Understand the Definition

    • Factorial means multiplying all positive integers from 1 through n.
    • By definition, 0! equals 1.
    • The input is non-negative, so we do not need to handle negative numbers.
  2. Step 2: Recursive Idea

    • Factorial has a direct recursive definition: n! = n * (n - 1)!.
    • The base case is 0! = 1 or 1! = 1.
    • This works, but an iterative loop avoids recursion depth concerns.
    def factorial(n):
        if n <= 1:
            return 1
        return n * factorial(n - 1)
  3. Step 3: Iterative Accumulation

    • Start with result = 1.
    • Multiply by each number from 2 through n.
    • If n is 0 or 1, the loop does not run and the answer remains 1.
  4. Step 4: Build the Loop

    • Use range(2, n + 1) so the final multiplier n is included.
    • Update the running product each iteration.
    • Return the product after all factors have been applied.
    def factorial(n):
        result = 1
        for value in range(2, n + 1):
            result *= value
        return result
  5. Step 5: Final Solution and Complexity

    • The solution directly follows the mathematical definition.
    • Time complexity is O(n).
    • Space complexity is O(1) because it uses one accumulator.
    def factorial(n: int) -> int:
        result = 1
        for value in range(2, n + 1):
            result *= value
        return result

FAQ