Recursion

Types of recursion, call stack, backtracking introduction


1. Introduction

Recursion is a programming technique in which a function calls itself to solve a smaller version of the same problem.

Instead of using loops, recursion repeatedly breaks a problem into smaller subproblems.

Example:

factorial(5)

= 5 × factorial(4)
= 5 × 4 × factorial(3)
= 5 × 4 × 3 × factorial(2)
= 5 × 4 × 3 × 2 × factorial(1)
= 120

2. Why Recursion?

Many problems are naturally recursive.

Examples:

  • Factorial
  • Fibonacci
  • Tree Traversal
  • Graph Traversal
  • Backtracking
  • Divide and Conquer
  • Dynamic Programming

Recursion often produces cleaner and more intuitive solutions.


3. How Recursion Works

Every recursive function must contain:

  1. Base Case
  2. Recursive Case

General Structure:

void recursiveFunction(int n){

    if(baseCondition)
        return;

    recursiveFunction(smallerProblem);
}

4. Recursion Tree

Example:

print(3);

Function:

void print(int n){

    if(n == 0)
        return;

    print(n - 1);
}

Execution:

print(3)
 |
print(2)
 |
print(1)
 |
print(0)

Then returns back:

print(0)
↑
print(1)
↑
print(2)
↑
print(3)

5. Base Case

The stopping condition.

Without a base case recursion never ends.

Example:

if(n == 0)
    return;

Without it:

fun(n-1);

will continue forever and cause:

StackOverflowError

6. Recursive Case

The part where the function calls itself.

Example:

return n * factorial(n - 1);

Problem size becomes smaller each time.


7. Call Stack

Every recursive call is stored in memory.

Example:

factorial(4)

Stack:

factorial(4)
factorial(3)
factorial(2)
factorial(1)

When base case is reached:

factorial(1)
returns

factorial(2)
returns

factorial(3)
returns

factorial(4)
returns

This mechanism is called stack unwinding.


8. Types of Recursion

  1. Direct Recursion
  2. Indirect Recursion
  3. Tail Recursion
  4. Head Recursion
  5. Tree Recursion
  6. Linear Recursion

9. Direct Recursion

A function directly calls itself.

Example:

void print(int n){

    if(n == 0)
        return;

    System.out.println(n);

    print(n - 1);
}

Output:

5
4
3
2
1

10. Indirect Recursion

Functions call each other.

Example:

void funA(int n){

    if(n <= 0)
        return;

    funB(n - 1);
}

void funB(int n){

    if(n <= 0)
        return;

    funA(n - 1);
}

11. Tail Recursion

Recursive call is the last statement.

Example:

void print(int n){

    if(n == 0)
        return;

    System.out.println(n);

    print(n - 1);
}

Recursive call:

print(n - 1);

is last.


12. Head Recursion

Recursive call happens first.

Example:

void print(int n){

    if(n == 0)
        return;

    print(n - 1);

    System.out.println(n);
}

Output:

1
2
3
4
5

13. Tree Recursion

Function makes multiple recursive calls.

Example:

void fun(int n){

    if(n == 0)
        return;

    fun(n - 1);
    fun(n - 1);
}

Recursion Tree:

         3
       /   \
      2     2
     / \   / \
    1  1  1  1

Complexity:

O(2^n)

14. Linear Recursion

Only one recursive call.

Example:

factorial(n)

Complexity:

O(n)

15. Recursive Problem Solving Strategy

Whenever solving recursively:

Step 1

Identify the smallest problem.

Step 2

Find base case.

Step 3

Assume smaller problem already solved.

Step 4

Use smaller solution to solve larger problem.


16. Basic Recursion Examples


public static void print(int n){

    if(n == 0)
        return;

    print(n - 1);

    System.out.println(n);
}

Output:

1
2
3
4
5

public static void print(int n){

    if(n == 0)
        return;

    System.out.println(n);

    print(n - 1);
}

Output:

5
4
3
2
1

17. Mathematical Problems


Factorial

Mathematical Formula:

n! = n \times (n-1)!

Java:

public static int factorial(int n){

    if(n == 0)
        return 1;

    return n * factorial(n - 1);
}

Example:

factorial(5)

5 × 4 × 3 × 2 × 1

120

Complexity:

O(n)

Sum of N Natural Numbers

Formula:

sum(n) = n + sum(n-1)

Java:

public static int sum(int n){

    if(n == 0)
        return 0;

    return n + sum(n - 1);
}

Example:

sum(5)

5+4+3+2+1

15

Power Function

Formula:

a^n = a × a^(n-1)

Java:

public static int power(int a,int n){

    if(n == 0)
        return 1;

    return a * power(a,n-1);
}

18. Array Problems


Sum of Array

Array:

1 2 3 4 5

Java:

public static int sum(int[] arr,int index){

    if(index == arr.length)
        return 0;

    return arr[index] +
           sum(arr,index+1);
}

Find Maximum Element

public static int max(int[] arr,int index){

    if(index == arr.length - 1)
        return arr[index];

    return Math.max(
        arr[index],
        max(arr,index+1)
    );
}

Reverse Array

public static void reverse(int[] arr,
                           int left,
                           int right){

    if(left >= right)
        return;

    int temp = arr[left];
    arr[left] = arr[right];
    arr[right] = temp;

    reverse(arr,left+1,right-1);
}

19. String Problems


Reverse String

public static String reverse(String str){

    if(str.length() == 0)
        return "";

    return reverse(str.substring(1))
           + str.charAt(0);
}

Input:

JAVA

Output:

AVAJ

Check Palindrome

public static boolean palindrome(
        String str,
        int left,
        int right){

    if(left >= right)
        return true;

    if(str.charAt(left)
       != str.charAt(right))
        return false;

    return palindrome(
            str,
            left+1,
            right-1);
}

20. Backtracking Introduction

Backtracking is an advanced form of recursion.

Steps:

  1. Choose
  2. Explore
  3. Undo

Applications:

  • N Queens
  • Sudoku Solver
  • Maze Problems
  • Permutations
  • Combinations

Example

Generate all subsets.

Array:

1 2

Subsets:

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

21. Time Complexity of Recursion

Depends on:

Number of Calls

and

Work per Call

General Formula:

Time =
(Number of Calls)
×
(Work per Call)

Examples:

ProblemComplexity
FactorialO(n)
SumO(n)
FibonacciO(2^n)
Binary SearchO(log n)

22. Space Complexity of Recursion

Depends on recursion depth.

Factorial:

factorial(5)

Stack:

5 calls

Space:

O(n)

Binary Search:

O(log n)

23. Common Interview Patterns


Divide and Conquer

Examples:

  • Merge Sort
  • Quick Sort
  • Binary Search

Backtracking

Examples:

  • N Queens
  • Sudoku
  • Rat in Maze

Tree Traversal

Examples:

  • DFS
  • Inorder
  • Preorder
  • Postorder

24. Recursion vs Iteration

FeatureRecursionIteration
Uses StackYesNo
MemoryMoreLess
ReadabilityBetterModerate
SpeedSlowerFaster
RiskStack OverflowNo

Factorial Iterative:

int result = 1;

for(int i=1;i<=n;i++){
    result *= i;
}

25. Common Interview Problems

Easy

  1. Factorial
  2. Power
  3. Sum of N Numbers
  4. Print Numbers
  5. Reverse String

Medium

  1. Fibonacci
  2. Palindrome
  3. Binary Search
  4. Reverse Array
  5. Tower of Hanoi

Hard

  1. Merge Sort
  2. Quick Sort
  3. N Queens
  4. Sudoku Solver
  5. Rat in Maze

Fibonacci (Most Asked)

Formula:

F(n)=F(n-1)+F(n-2)

Java:

public static int fib(int n){

    if(n <= 1)
        return n;

    return fib(n-1) +
           fib(n-2);
}

Example:

fib(5)

5

Sequence:

0 1 1 2 3 5

Complexity:

O(2^n)

Tower of Hanoi

Rules:

  1. Move one disk at a time.
  2. Larger disk cannot be placed on smaller disk.
  3. Use auxiliary rod.

Recursive Solution:

public static void hanoi(
        int n,
        char source,
        char helper,
        char destination){

    if(n == 1){

        System.out.println(
            source + " -> " +
            destination
        );

        return;
    }

    hanoi(
        n-1,
        source,
        destination,
        helper
    );

    System.out.println(
        source + " -> " +
        destination
    );

    hanoi(
        n-1,
        helper,
        source,
        destination
    );
}

Complexity:

O(2^n)

26. Revision Summary

Recursion:

  • Function calling itself
  • Solves smaller version of same problem

Must Have:

  1. Base Case
  2. Recursive Case

Important Types:

  1. Direct Recursion
  2. Indirect Recursion
  3. Tail Recursion
  4. Head Recursion
  5. Tree Recursion

Must Know Problems:

  1. Factorial
  2. Fibonacci
  3. Power
  4. Reverse String
  5. Palindrome
  6. Binary Search
  7. Merge Sort
  8. Quick Sort
  9. Tower of Hanoi
  10. N Queens

Important Interview Patterns:

  • Divide and Conquer
  • Backtracking
  • DFS Traversal
  • Tree Recursion

Learning Path:

Recursion Basics → Factorial → Fibonacci → Arrays → Strings → Binary Search → Merge Sort → Quick Sort → Backtracking → Trees → Dynamic Programming