factorial

Medium · Recursion · 3 test cases

Given a non-negative integer n, return the factorial of n (n!). Factorial of a number is the product of all positive integers less than or equal to n.

Examples

factorial(5) → 120
factorial(3) → 6
factorial(0) → 1

Starter code

function factorial(n) {

}

Complexity of the optimal solution

Time O(n), space O(n). The recursive function calls itself n times until it reaches the base case. This results in a time complexity of O(n). Each function call is added to the call stack, leading to a space complexity of O(n) as well.

Solve factorial in the browser