Recursion Interview Questions

Recursion is frequently tested in technical interviews, as it showcases a candidate’s problem-solving skills and understanding of fundamental concepts like divide and conquer, backtracking, and dynamic programming.
Share on :

Recursion is a powerful concept in programming that allows a function to call itself to solve smaller instances of a problem. While it can simplify solutions for certain types of problems, it requires a deep understanding of breaking problems down into base cases and recursive cases. Recursion is frequently tested in technical interviews, as it showcases a candidate’s problem-solving skills and understanding of fundamental concepts like divide and conquer, backtracking, and dynamic programming.

In this blog, we will explore the top recursion interview questions, complete with Python code examples to help you prepare for interviews.

1. Factorial of a Number

Problem Statement:
Write a recursive function to calculate the factorial of a given number n. Factorial of a number is the product of all positive integers less than or equal to n.

  • Concept: Recursion with base case
  • Difficulty Level: Easy

Approach:
Define a base case where n = 0 or n = 1 returns 1. For other values, recursively multiply n by the factorial of n-1.

def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

Example:

n = 5
print(factorial(n))  # Output: 120

2. Fibonacci Sequence

Problem Statement:
Write a recursive function to find the nth Fibonacci number. The Fibonacci sequence is defined as F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n > 1.

  • Concept: Recursion with overlapping subproblems
  • Difficulty Level: Easy

Approach:
The base cases are F(0) = 0 and F(1) = 1. Recursively compute F(n) as the sum of F(n-1) and F(n-2).

def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

Example:

n = 6
print(fibonacci(n))  # Output: 8

3. Sum of Digits

Problem Statement:
Given a positive integer n, recursively find the sum of its digits.

  • Concept: Breaking down the number by modulo and division
  • Difficulty Level: Easy

Approach:
Base case is when n becomes 0. For other values, take the last digit (n % 10) and add it to the sum of digits of n // 10.

def sum_of_digits(n):
    if n == 0:
        return 0
    else:
        return n % 10 + sum_of_digits(n // 10)

Example:

n = 1234
print(sum_of_digits(n))  # Output: 10

4. Power of a Number

Problem Statement:
Write a recursive function to compute x^n, where x is the base and n is the exponent.

  • Concept: Divide and conquer
  • Difficulty Level: Medium

Approach:
The base case is when n = 0, which returns 1. For even n, compute power(x, n//2) and square it. For odd n, multiply x by the result of power(x, n-1).

def power(x, n):
    if n == 0:
        return 1
    elif n % 2 == 0:
        half = power(x, n // 2)
        return half * half
    else:
        return x * power(x, n - 1)

Example:

x = 2
n = 5
print(power(x, n))  # Output: 32

5. Reverse a String

Problem Statement:
Write a recursive function to reverse a string.

  • Concept: String manipulation
  • Difficulty Level: Easy

Approach:
The base case is when the string is empty. For other cases, take the last character and append it to the result of reversing the rest of the string.

def reverse_string(s):
    if len(s) == 0:
        return s
    else:
        return reverse_string(s[1:]) + s[0]

Example:

s = "hello"
print(reverse_string(s))  # Output: "olleh"

6. Binary Search (Recursive)

Problem Statement:
Given a sorted array of integers, use recursion to implement binary search to find the target value. If the target exists, return its index, otherwise return -1.

  • Concept: Divide and conquer
  • Difficulty Level: Medium

Approach:
Recursively divide the array into halves, checking if the target is in the left or right half.

def binary_search(arr, target, low, high):
    if low > high:
        return -1
    mid = (low + high) // 2
    if arr[mid] == target:
        return mid
    elif arr[mid] > target:
        return binary_search(arr, target, low, mid - 1)
    else:
        return binary_search(arr, target, mid + 1, high)

Example:

arr = [1, 2, 3, 4, 5, 6, 7]
target = 5
print(binary_search(arr, target, 0, len(arr) - 1))  # Output: 4

7. Tower of Hanoi

Problem Statement:
Solve the Tower of Hanoi problem for n disks. The objective is to move all disks from the source rod to the destination rod using an auxiliary rod, following these rules:

  1. Only one disk can be moved at a time.
  2. A disk can only be placed on top of a larger disk.
  • Concept: Divide and conquer
  • Difficulty Level: Hard

Approach:
Recursively move n-1 disks from the source to the auxiliary rod, then move the nth disk to the destination, and finally move n-1 disks from the auxiliary to the destination.

def tower_of_hanoi(n, source, destination, auxiliary):
    if n == 1:
        print(f"Move disk 1 from {source} to {destination}")
        return
    tower_of_hanoi(n - 1, source, auxiliary, destination)
    print(f"Move disk {n} from {source} to {destination}")
    tower_of_hanoi(n - 1, auxiliary, destination, source)

Example:

n = 3
tower_of_hanoi(n, 'A', 'C', 'B')

Output:

Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

8. Permutations of a String

Problem Statement:
Write a recursive function to print all the permutations of a given string.

  • Concept: Backtracking
  • Difficulty Level: Medium

Approach:
Swap characters recursively to generate permutations by fixing one character at a time and permuting the rest.

def permute_string(s, l, r):
    if l == r:
        print(''.join(s))
    else:
        for i in range(l, r + 1):
            s[l], s[i] = s[i], s[l]  # Swap
            permute_string(s, l + 1, r)
            s[l], s[i] = s[i], s[l]  # Backtrack

Example:

s = list("ABC")
permute_string(s, 0, len(s) - 1)

Output:

ABC
ACB
BAC
BCA
CAB
CBA

9. Generate All Subsets of a Set

Problem Statement:
Write a recursive function to generate all subsets of a given set of distinct integers.

  • Concept: Backtracking
  • Difficulty Level: Medium

Approach:
Use recursion to either include or exclude each element to form all possible subsets.

def generate_subsets(nums, index, current, result):
    if index == len(nums):
        result.append(current[:])
        return
    # Exclude the current element
    generate_subsets(nums, index + 1, current, result)
    # Include the current element
    current.append(nums[index])
    generate_subsets(nums, index + 1, current, result)
    current.pop()  # Backtrack

Example:

nums = [1, 2, 3]
result = []
generate_subsets(nums, 0, [], result)
print(result)

Output:

[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]

10. Combination Sum

Problem Statement:
Given an array of distinct integers and a target sum, find all unique combinations of numbers where the numbers sum up to the target.

  • Concept: Backtracking
  • Difficulty Level: Hard

Approach:
Use recursion to build combinations that add up to the target, and explore all possible subsets.

def combination_sum(candidates, target):
    result = []
    def backtrack(remain, combo, start):
        if remain == 0:
            result.append(list(combo))
            return
        elif remain < 0:
            return
        for i in range(start, len(candidates)):
            combo.append(candidates[i])
            backtrack(remain - candidates[i], combo, i)
            combo.pop()  # Backtrack
    
    backtrack(target, [], 0)
    return result

Example:

candidates = [2, 3, 6, 7]
target = 7
print(combination_sum(candidates, target))

Output:

[[2, 2, 3], [7]]

Conclusion

Recursion is an essential tool for solving complex problems by breaking them down into simpler subproblems. Understanding these top recursion interview questions will help you master recursion concepts such as divide and conquer, backtracking, and dynamic programming, which are frequently used in technical interviews. By practicing these problems, you’ll be well-prepared to handle recursive solutions in coding challenges and interviews.

FAQs

1. When should I use recursion?
Recursion is useful when a problem can be divided into smaller subproblems, especially when the solution has a repetitive structure, such as in tree traversal, dynamic programming, or combinatorial problems.

2. How can I avoid stack overflow in recursion?
To avoid stack overflow, ensure that your recursive function has a well-defined base case and consider using iterative solutions or tail recursion if the recursion depth is too large.

3. What is backtracking in recursion?
Backtracking is a recursive technique used to solve problems by trying all possible solutions and backtracking to previous states if a solution does not work. It’s commonly used in problems like combinations, permutations, and Sudoku.

4. How can I optimize recursive functions?
You can optimize recursive functions by using memoization or dynamic programming to store intermediate results and avoid redundant calculations, especially for overlapping subproblems (e.g., Fibonacci sequence).

5. Are recursive solutions always better?
No, recursive solutions are not always better. For some problems, an iterative approach may be more efficient in terms of time and space complexity. Recursive solutions can lead to stack overflow for deep recursions.