Calculating the factorial of number recursively (Time and Space analysis)

“grayscale photo of wood trunks” by John Westrock on Unsplash

The factorial of a number is defined as:

f(n) = n * f(n-1) → for all n >0
f(0) = 1 → for n = 0

C++ code:

Time complexity

If we look at the pseudo-code again, added below for convenience. Then we notice that:

  • factorial(0) is only comparison (1 unit of time)
  • factorial(n) is 1 comparison, 1 multiplication, 1 subtraction and time for factorial(n-1)

From the above analysis we can write:

T(n) = T(n — 1) + 3
T(0) = 1

Space complexity

For every call to the recursive function, the state is saved onto the call stack, till the value is computed and returned to the called function.

Here we don’t assign an explicit stack, but an implicit call stack is maintained

f(6) → f(5) → f(4) → f(3) → f(2) → f(1) → f(0)
f(6) → f(5) → f(4) → f(3) → f(2) → f(1)
f(6) → f(5) → f(4) → f(3) → f(2)
f(6) → f(5) → f(4) → f(3)
f(6) → f(5) → f(4)
f(6) → f(5)

The function in bold is the one currently being executed. As you can see for f(6) a stack of 6 is required till the call is made to f(0) and a value is finally computed. Hence for factorial of N, a stack of size N will be implicitly allocated for storing the state of the function calls.

The space complexity of recursive factorial implementation is O(n)

If you like the post and want to learn more about Data Structures and Algorithms, Low-Level Design and High-Level Design to crack top product company interviews and get into FAANG, then I would highly recommend joining Scaler, where I am an Alumni and owe a lot of my success to them. Their curriculum is highly structured with teachers who are ex-Googlers, etc. employees. You also get mentorship from the very best, working in your dream tech companies like FAANG. If you use the link my link to join Scaler, then you will get a course discount of Rs. 10,000 and I will get a cashback of the same amount. Do check out their course and take advantage of the classes provided by them to boost your career from the comfort of your home.

For more coding related tips and walkthroughs check out my content. Happy coding !!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store