Factorial

Problem Link : factorial


Problem Statement

You are given a positive integer n.
Your task is to compute the factorial of n.

The factorial of a non-negative integer n is defined as:
n! = 1 × 2 × 3 × ... × (n - 1) × n
Special case: 0! = 1


Examples

Example 1:

Example 2:


Constraints

Note: Since 12! = 479001600, the result safely fits in a 32-bit signed integer.


Intuition

The factorial of n can be computed using:

This problem uses the recursive approach, which is concise and elegant for small values of n.


Approach (Recursive)

  1. Base case:

    • If n <= 1, return 1 (since 0! = 1 and 1! = 1)
  2. Recursive step:

    • Return n × factorial(n - 1)

Java Code

class Solution {
    static int factorial(int n) {
        if (n <= 1) return 1;          // Base case
        return n * factorial(n - 1);   // Recursive case
    }
}

Dry Run

Input: n = 4

Call Stack:

factorial(4)
→ 4 * factorial(3)
→ 4 * (3 * factorial(2))
→ 4 * (3 * (2 * factorial(1)))
→ 4 * (3 * (2 * 1)) = 24

Output: 24


Time Complexity

Space Complexity


Alternative (Iterative Approach)

An iterative version avoids recursion stack overhead:

static int factorial(int n) {
    int result = 1;
    for (int i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}

Conclusion

The recursive approach is clean and appropriate within the problem’s constraint range. For larger values of n, the iterative approach would be more memory-efficient, but for n ≤ 12, recursion is perfectly valid and intuitive.