Back to Practice Dashboard
Python BasicsMedium
Factorial using recursion
Learn how to solve the 'Factorial using recursion' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Medium
Write a function factorial(n) that computes the factorial of a non-negative integer n using recursion. The factorial of n (written as n!) is the product of all positive integers from 1 to n. By definition, 0! = 1. The function should return the factorial as an integer.
Constraints
- •0 <= n <= 20
Examples
Example 1
Input
n = 5
Output
120
Explanation
5! = 5 * 4 * 3 * 2 * 1 = 120.
Example 2
Input
n = 0
Output
1
Explanation
0! is defined as 1.
Example 3
Input
n = 7
Output
5040
Explanation
7! = 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5040.
Need a Hint?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.