101 Logo
onenoughtone

Solution Approach

Solution Overview

There are 3 main approaches to solve this problem:

  1. Recursive Approach - Complex approach
  2. Iterative Approach - Complex approach
  3. Tail-Recursive Approach - Complex approach

Approach 1: Recursive Approach

The recursive approach directly implements the mathematical definition of factorial: n! = n × (n-1)!. This approach is elegant and intuitive, making it a great example of how recursion can simplify code.

Algorithm:

  1. Define a base case: if n is 0 or 1, return 1 (since 0! = 1! = 1).
  2. For n > 1, return n multiplied by the factorial of (n-1).
  3. The recursion will continue until it reaches the base case, then unwind to compute the final result.

Time Complexity:

O(n)

We make n recursive calls, each doing O(1) work.

Space Complexity:

O(n)

The recursion stack will have at most n frames, each using constant space.

Approach 2: Iterative Approach

The iterative approach uses a loop to calculate the factorial. This approach avoids the overhead of recursive function calls and potential stack overflow for large inputs.

Algorithm:

  1. Initialize a result variable to 1.
  2. Iterate from 1 to n (or from n down to 1).
  3. In each iteration, multiply the result by the current number.
  4. After the loop completes, return the result.

Time Complexity:

O(n)

We perform n multiplications, each taking O(1) time.

Space Complexity:

O(1)

We only use a constant amount of extra space, regardless of the input size.

Approach 3: Tail-Recursive Approach

The tail-recursive approach is a variation of the recursive approach where the recursive call is the last operation in the function. This allows some compilers to optimize the recursion into iteration, avoiding stack overflow.

Algorithm:

  1. Define a helper function that takes two parameters: n and an accumulator.
  2. Base case: if n is 0 or 1, return the accumulator.
  3. Recursive case: call the helper function with (n-1) and (n * accumulator).
  4. Initialize the main function by calling the helper with the input n and accumulator set to 1.

Time Complexity:

O(n)

We make n recursive calls, each doing O(1) work.

Space Complexity:

O(n) or O(1)

O(n) in languages without tail call optimization, O(1) in languages with tail call optimization.

Pseudocode

solution.pseudo
1
2
3
4
5
6
7
function factorial(n):
// Base case
if n == 0 or n == 1:
return 1
// Recursive case
return n * factorial(n - 1)
ProblemSolutionCode
101 Logo
onenoughtone