Recursion – Mastering Self-Referential Problem Solving

Recursion is one of the most powerful and elegant tools in programming, or even in competitive programming — but it can seem confusing at first.

In this guide, you’ll learn what recursion is, how to identify recursive problems, how to approach solving them step by step, and how to build your recursive thinking muscle.

What is Recursion?

Recursion is a programming technique where a function calls itself to solve a smaller version of the original problem.

  • It’s like solving a puzzle by solving a smaller version of the same puzzle.
  • If a problem can be broken down into smaller, similar subproblems, it can usually be solved using recursion.

The Structure of a Recursive Function

Every recursive function has two main parts:

  • Base Case/Stopping criteria: It tells the function when to stop calling itself. If there’s no base case, the function will call itself forever and crash.
  • Recursive Case: This is where the function calls itself with a smaller version of the problem.

def any_recursive(n):

  if Stopping criteria: 
    return something
    
  return some_result (operation like +,- etc or even nothing) any_recursive(n')
  
  #Example  return some_result + any_recursive(n')
  #Example  return some_result * any_recursive(n')
  #Example  return any_recursive(n')
Python

The stopping condition is very important; without this, the program will end in an infinite loop

Tier 1: Anchor Problems

Sum

Find the Sum of all numbers from 1 to n

Solution

Step 1: Can it be solved recursively or not? Can the problem be broken into smaller parts?

sum(5) => 5 + sum(4) => 4 + sum(3) => 3 + sum(2) => 2 + sum(1) => 1 + sum(0)
Python

Step 2: Stopping criteria

At sum(0), we should stop and return 0

if n == 0:
  return 0
Python

Step 3: Recursive Case

return n + sum(n-1) #  5 + sum(4) 
Python

Code

def sum(n):
    if n==0:
        return 0
    return n+sum(n-1)

print(sum(5)) #15
Python

Factorial

Solution

Step 1: Can it be solved recursively or not? Can the problem be broken into smaller parts

factorial(5) => 5 * factorial(4) => 4*factorial(3) => 3*factorial(2) => 2*factorial(1) => 1*factorial(0)
Python

Step 2: Stopping criteria

if n==0:
  return 1
Python

Step 3: Recursive Case

return n * factorial(n-1) #5*factorial(4)
Python

Code

def factorial(n):
    if n==0:
        return 1

    return n * factorial(n-1)

print(factorial(5)) #120
Python

Count Down

def count_down(n):

    if n==0:  # Base Case
        return

    print(n)
    return count_down(n-1) # Recursive Call happens first

count_down(5)

'''
5
4
3
2
1
'''
Python

Count Up

def count_up(n):
    if n == 0:  # Base Case
        return
    count_up(n - 1)  # Recursive Call happens first
    print(n)                # Then we print

count_up(5)

'''
1
2
3
4
5
'''
Python

Key Difference Between the Two:

  • In countdown, you print before the recursive call.
  • In countup, you print after the recursive call.

Reverse a string

Step 1: Can the problem be broken into smaller parts?

reverse_string("hello")
= reverse_string("ello") + "h"
= reverse_string("llo") + "e" + "h"
= reverse_string("lo") + "l" + "e" + "h"
= reverse_string("o") + "l" + "l" + "e" + "h"
= "o" + "l" + "l" + "e" + "h"
= "olleh"
Python

Step 2: Stopping criteria

If the string is empty or has only one character, return it.

if len(s) <= 1:
    return s
Python

Step 2: Recursive Case

Take the first character, reverse the rest of the string recursively, and put the first character at the end.

Way 1

return reverse_string(s[1:]) + s[0]

''' 
reverse_string("hello")
= reverse_string("ello") + "h"
= reverse_string("llo") + "e" + "h"
= reverse_string("lo") + "l" + "e" + "h"
= reverse_string("o") + "l" + "l" + "e" + "h"
= "o" + "l" + "l" + "e" + "h"
= "olleh"
'''
Python

Code

def reverse(s):
    length = len(s)
    if len(s)<=1:
        return s
    return  s[length-1] + reverse(s[:length-1])
Python

Way 2:

return  s[length-1] + reverse(s[:length-1])

'''
reverse_string("hello")
= o + reverse_string("hell")
= o + l + reverse_string("hel")
= o + l + l + reverse_string("he")
= o + l + l + e + reverse_string("h")
= "o" + "l" + "l" + "e" + "h"
= "olleh"
'''
Python

Code


def reverse_string(s):
    if len(s) <= 1:        # Base Case
        return s
    return reverse_string(s[1:]) + s[0]  # Recursive Case
Python

Check if a string is a palindrome

Step 1: Stopping Criteria

If the string has 0 or 1 character, it’s a palindrome.

Step 2: Recursive Case

  • If the first and last characters are the same, check the substring in between.
  • Otherwise, it’s not a palindrome.
def palindrome(s):
    
    if len(s)<=1:
        return True
    if s[0]!=s[-1]:
        return False

    return palindrome(s[1:-1])
Python

Find the maximum element in a list

Way 1 :

  • Finding max of 0th and last index.
  • Then remove the last index element; repeat this
def find_max(lst):
    if len(lst)==1:
        return lst[0]

    if lst[0]<lst[-1]:
        lst[0],lst[-1] = lst[-1],lst[0]

    return find_max(lst[:-1])
Python

Way 2: Better approach than way 1

def find_max(lst):
    if len(lst) == 1:  # Base case
        return lst[0]

    rest_max = find_max(lst[1:])  # Recursive call
    return max(lst[0], rest_max)
Python

Drawbacks of ways 1 and 2

  • You’re modifying the list in-place, which may not be safe in all contexts.
  • Slicing creates a new list every time, so it’s not the most efficient.
  • Less intuitive than a direct comparison-based approach.

Way 3: Best

To avoid slicing altogether, we can use indexes to track where we are in the list — this way, we reuse the same list and avoid extra memory usage.

def find_max(lst, idx=0):
    if idx == len(lst) - 1:
        return lst[idx]
    
    max_rest = find_max(lst, idx + 1)
    return max(lst[idx], max_rest)
Python

Count digits of a number

def count_digits(n):
    n = n//10

    if n == 0:
        return 1
    return 1 + count_digits(n) if n > 0 else 0
Python

def count_digits(n):
    if n <1:
        return 0

    n = n//10
    return 1 + count_digits(n)
Python

Fibonacci series (nth term)

f(0) => 0
f(1) => 1
f(2) => f(1) + f(0)
f(3) => f(2) + f(3)
f(4) => f(3) + f(2)
f(5) => f(4) + f(3)
Python

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

  • The basic recursive version is very slow for large n because it recalculates the same values many times.
  • Instead of calculating the same values again and again. What if we can memoise the results and use that?
  • Will see that in Dynamic Programming

Tier 2: Variation Problems

Power of a number (e.g., 2^n)

def power_two(n):
    if n ==1:
        return 1
    return 2*power_two(n-1) 
Python

Any Base


def power(base, exponent):
    if exponent == 0:
        return 1
    return base * power(base, exponent - 1)
Python

Sum of elements in a list

Way 1

def sum_list(lst):

    if len(lst)==0:
        return 0

    return lst[0]+sum_list(lst[1:])
Python

Using lst[1:] creates a new list at each recursive call, which is fine for small lists but not optimal for large ones because it uses extra memory.

Way 2:


def sum_list(lst, idx=0):
    if idx == len(lst):
        return 0
    return lst[idx] + sum_list(lst, idx + 1)

Python

Tier 3 — Hard/Edge Problems

Generate all permutations of a string or list(Don’t use this; use backtracking)

def permute(lst):
    if len(lst) == 1:
        return [lst]
    
    result = []
    for i in range(len(lst)):
        current = lst[i]
        remaining = lst[:i] + lst[i+1:]
        for p in permute(remaining):
            result.append([current] + p)
    
    return result


permutations = permute([1, 2, 3, 4])
for p in permutations:
    print(p)


'''
Output

[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
....
....

'''
Python

Permutation with duplication(Don’t use this; use backtracking)

Way 1:

def permute_unique(lst):
    if len(lst) == 1:
        return [lst]

    result = set()
    for i in range(len(lst)):
        current = lst[i]
        remaining = lst[:i] + lst[i+1:]
        for p in permute_unique(remaining):
            result.add(tuple([current] + p))  # tuple to store in set

    return [list(p) for p in result]
Python

Instead of using a list for result, we can use a set

Why not just add the list directly?

result.add(tuple([current] + p))
Python

Because lists are mutable and cannot be added to a set.

set.add([1, 2, 3])  # ❌ TypeError: unhashable type: 'list'
Python

But tuples are immutable and can be added to a set:

set.add((1, 2, 3))  # ✅ Works fine
Python

Convert back to a list

return [list(p) for p in result]
Python

Way 2 :

def permute_unique(lst):
    if len(lst) == 0:
        return [[]]

    lst.sort()
    result = []

    prev = None
    for i in range(len(lst)):
        if lst[i] == prev:
            continue  # Skip duplicates

        rest = lst[:i] + lst[i+1:]
        for p in permute_unique(rest):
            result.append([lst[i]] + p)
        
        prev = lst[i]

    return result
Python

How it works:

  • lst.sort() puts duplicate elements next to each other.
  • prev tracks the last value used at this level.
  • If we see the same value again, we skip it to avoid generating the same permutation.

Instead of all this, we can also use backtracking.

More to practice

  • Binary search (recursive version)
  • Count occurrences of an element in a list
  • Product of list elements
  • Find GCD (Greatest Common Divisor) using recursion
  • Check if an array is sorted
  • Convert decimal to binary
  • Replace all occurrences of a character in a string
  • Generate all subsets (power set) of a set
  • Tower of Hanoi
  • N-th Catalan number
  • Maze solver (backtracking)
  • N-Queens problem
  • Recursive tree/graph traversal (DFS)
  • Sudoku solver (backtracking)
  • Word break problem
  • Subset sum problem

About Puneet Verma

Puneet Verma is a software developer specialising in backend architecture, Dynamic Programming, and SaaS solutions. He focuses on building optimised, scalable applications and sharing deep-dive technical tutorials to help developers master complex algorithmic patterns.

1 thought on “Recursion – Mastering Self-Referential Problem Solving”

Leave a Comment