Grokking the Art of Recursion for Coding Interviews
Ask Author
Back to course home

0% completed

Solution: Factorial
Table of Contents

Problem Statement

Solution

Code

Time and Space Complexity

Problem Statement

Calculate the Factorial of a Positive Number Using Recursion.

The factorial of a non-negative integer N, denoted as N!, is the product of all positive integers less than or equal to N. The factorial of 0 is defined as 1.

Here is what the example input/output looks like:

InputExpected OutputExplanation
Number = 5Factorial = 120The factorial of 5 is calculated as 5 _ 4 _ 3 _ 2 _ 1 = 120.
Number = 7Factorial = 5040The factorial of 7 is calculated as 7 _ 6 _ 5 _ 4 _ 3 _ 2 _ 1 = 5040.
Number = 1Factorial = 1The factorial of 1 is 1 itself.

Solution

The algorithm to calculate the factorial of a positive number using recursion can be defined as follows:

  1. If the given number is 0 or 1, return 1 (base case).
  2. Otherwise, return the product of the number and the recursive call to calculate the factorial of the number minus 1.

The recursive approach works by breaking down the problem into smaller subproblems. We calculate the factorial of a number by multiplying it with the factorial of the number minus 1. This process continues until the base case is reached, where the number is 0 or 1. The base case stops the recursion and returns 1.

By multiplying the numbers in decreasing order, we ensure that each number is multiplied with the product of the previous numbers, eventually giving us the factorial of the given number.

Example dry run to calculate Factorial of 5
Example dry run to calculate Factorial of 5

Code

Here is the code for this algorithm:

Python3
Python3

. . . .

Time and Space Complexity

The time complexity of the algorithm is O(N) since we make N recursive calls, where N is the given input.

The space complexity of the algorithm is also O(N) because the maximum depth of the recursion is N. Each recursive call adds a new stack frame, consuming additional space on the call stack.

Mark as Completed

Table of Contents

Problem Statement

Solution

Code

Time and Space Complexity