Introduction

Factorial means:

  • multiplying all numbers
  • from 1 to n

Factorial of:

  • 5 = 5 × 4 × 3 × 2 × 1

Example:

5! = 120 

Explanation:

5 × 4 × 3 × 2 × 1
= 120

This problem is one of the most important applications of:

Recursion 

Constraints

0 <= n <= 20 

Approach 1 : Iterative Solution

Explanations:

Explanation:

The idea is:

  • start from 1
  • multiply numbers one by one

Steps:

  1. Initialize answer as 1.
  2. Traverse from 1 to n.
  3. Multiply values.
  4. Print result.

This approach:

  • avoids recursion
  • is beginner friendly

Dry Run

n = 5
result = 1
1 × 2 = 2
2 × 3 = 6
6 × 4 = 24
24 × 5 = 120

Practice :

Complexity Analysis :

Time Complexity:- O(n)
Explanation :

Loop runs n times.
Space Complexity:- O(1) Explanation :
No extra space is used.

Approach 2 : Recursive Solution

Explanations:

Explanation:

This is the most important recursion-based solution.

The idea is:

  • factorial(n)
  • equals n × factorial(n-1)

Base Case:

  • factorial(0) = 1

Recursive Case:

  • factorial(n) = n × factorial(n-1)

Dry Run

factorial(5)
5 × factorial(4)
5 × 4 × factorial(3)
5 × 4 × 3 × factorial(2)
5 × 4 × 3 × 2 × factorial(1)
5 × 4 × 3 × 2 × 1 = 120

Practice :

Complexity Analysis

Time Complexity:- O(n)
Explanation :
Recursive calls run n times.
Space Complexity:- O(n) Explanation :
Recursion stack is used.

Why This Problem is Important

This problem builds the foundation for:

  • Recursion
  • Function calls
  • Stack understanding
  • Mathematical problems
  • Recursive thinking

Real-World Applications

Factorial concepts are used in:

  • Mathematics
  • Probability
  • Permutations & combinations
  • Algorithm analysis
  • Scientific computing

Common Beginner Mistakes

  • Missing base case
  • Infinite recursion
  • Wrong recursive formula
  • Stack overflow for large n
  • Incorrect multiplication order

Interview Tip

Interviewers often expect:

  • recursion understanding
  • proper base case
  • recursive flow explanation
  • iterative vs recursive comparison

Always explain:

  • base case
  • recursive case
  • recursion stack flow

Related Questions

  • Fibonacci
  • Power Function
  • Sum of Digits
  • Reverse String
  • Tower of Hanoi

Final Takeaway

The Factorial problem is one of the most important beginner recursion problems.

It teaches:

  • recursion basics
  • recursive thinking
  • function calls
  • stack behavior

Understanding this problem builds a strong foundation for:

  • advanced recursion problems
  • dynamic programming
  • interview-level algorithms.