Problems › Recursion

Factorial

Difficulty: Easy · Topic: Recursion

Return n! = n × (n-1) × ... × 1, with 0! = 1. You may write it recursively or iteratively, but think about the base case.

Examples

factorial(0)
→ 1

The empty product is 1.

factorial(1)
→ 1
factorial(5)
→ 120

5 × 4 × 3 × 2 × 1.

Target complexity: time O(n), space O(n)

Write your solution in Python and run it against hidden tests right on this page. Progressive hints and Python + C++ reference solutions are included.

Learn the idea first: the lesson for this problem.

More Recursion problems