Data Structures & Algorithms chapters (13)
  1. 01Introduction to DSA
  2. 02Arrays & Strings Algorithms
  3. 03Searching & Sorting Algorithms
  4. 04Asymptotic Analysis & Complexity
  5. 05Linked Lists
  6. 06Stacks & Queues
  7. 07Hashing & Hash Tables
  8. 08Recursion & Backtracking
  9. 09Binary Trees & BST
  10. 10Heaps & Priority Queues
  11. 11Graphs & Graph Algorithms
  12. 12Greedy Algorithms & Bit Manipulation
  13. 13Dynamic Programming (DP)

Chapter 08

Recursion & Backtracking

3 topics · 2 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Recursion solves a problem by reducing it to smaller instances of itself with a base case.

Backtracking builds candidates incrementally, abandons (prunes) branches that cannot succeed, and undoes choices to explore alternatives.

Backtracking is the standard tool for combinatorial search; recursion tracing is a frequent GATE question.

Sudoku solvers, constraint satisfaction, path finding in mazes, generating test cases, parsing.

1

Recursion & Base Cases

A recursive function calls itself on a strictly smaller input and stops at a base case that returns directly. Correctness needs (1) a base case, (2) progress toward it, and (3) a correct combination of sub-results.

In short: Solve a smaller copy of the same problem and stop when the problem is trivially small.

Recursion call stack: each call waits for the next to return
Recursion call stack: each call waits for the next to return

Think about it

Foundation for trees, DP, divide and conquer and backtracking.

Missing or unreachable base case gives infinite recursion and stack overflow (RecursionError at ~1000 frames in CPython).

Recursion tree: number of nodes is the number of calls, depth is the stack space.

Factorial: T(n)=T(n-1)+1 = O(n) time and stack.

Fibonacci naive T(n)=T(n-1)+T(n-2)+1 = O(phi^n) is exponential because subproblems repeat: fix with memoization (O(n)).

Power by squaring: pow(x,n)=pow(x,n/2)^2 gives O(log n); compute pow(x,n//2) once, not twice (which would be O(n)).

Tower of Hanoi: T(n)=2T(n-1)+1 = 2^n - 1 moves.

Tail recursion can be replaced by a loop (no TCO in CPython/Java).

Mutual recursion and indirect recursion also use the stack.

Convert recursion to iteration with an explicit stack.

Types: linear, binary (tree), nested (Ackermann).

GATE trace questions: carefully evaluate return values bottom-up and track global/static variables that persist across calls.

Key points

  • Base case: Input for which the answer is returned without recursion.
  • Recursion depth: Maximum nested calls = stack space.
  • Memoization: Cache results of subproblems to avoid recomputation.

Example

Code
Recursion patterns:
def power(x, n):                 # O(log n)
    if n == 0: return 1
    half = power(x, n // 2)      # compute once!
    return half * half if n % 2 == 0 else half * half * x

def hanoi(n, a, b, c, moves):    # 2^n - 1 moves
    if n == 0: return
    hanoi(n - 1, a, c, b, moves)
    moves.append((a, c))
    hanoi(n - 1, b, a, c, moves)

from functools import lru_cache
@lru_cache(None)
def fib(n):                      # O(n) time, O(n) stack
    return n if n < 2 else fib(n - 1) + fib(n - 2)
2

Subsets & Combinations

Subset generation enumerates all 2^n subsets by deciding for each element include or exclude. Combination generation picks k of n elements (C(n,k) results) using a start index to avoid reordering duplicates. Permutations (n! results) use a used[] array or swapping.

In short: At every element ask "take it or skip it?" and recurse; undo the choice when coming back.

Include or skip each element (backtracking)

Think about it

Template covers dozens of interview problems; duplicate-skipping rule is a common trap.

Template: choose x, recurse on the remaining, unchoose (path.

pop()).

Subsets: T(n)=2T(n-1)+O(1) -> 2^n leaves, O(n*2^n) total when copying each subset.

Combinations: loop i from start..

n and recurse with i+1 so each set is produced once in increasing order; prune when remaining elements < still needed (n - i + 1 < k - len(path)).

Subsets II / combination sum with duplicates: sort first and skip if i > start and a[i] == a[i-1] at the same level.

Combination sum (unlimited reuse): recurse with i instead of i+1.

Permutations: n!

results, O(n * n!

); with duplicates, sort and skip a[i]==a[i-1] when a[i-1] is unused.

Bitmask alternative for subsets: iterate mask 0..

2^n-1.

Space: O(n) depth plus output.

Always append a COPY of path (path[:]) to results; appending the reference gives empty lists later.

Key points

  • Choose-explore-unchoose: Add element, recurse, remove element.
  • Pruning: Cutting branches that cannot lead to a valid answer.
  • Start index: Prevents generating the same combination in different orders.

Example

Code
Backtracking templates:
def subsets(nums):
    nums.sort(); res, path = [], []
    def go(start):
        res.append(path[:])               # copy!
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue                  # skip duplicates at same level
            path.append(nums[i])
            go(i + 1)
            path.pop()
    go(0)
    return res

def combine(n, k):
    res, path = [], []
    def go(start):
        if len(path) == k:
            res.append(path[:]); return
        for i in range(start, n - (k - len(path)) + 2):   # pruning
            path.append(i); go(i + 1); path.pop()
    go(1)
    return res

def permutations(nums):
    res, used, path = [], [False] * len(nums), []
    def go():
        if len(path) == len(nums):
            res.append(path[:]); return
        for i in range(len(nums)):
            if used[i]: continue
            used[i] = True; path.append(nums[i])
            go()
            path.pop(); used[i] = False
    go()
    return res
3

N-Queens Problem

Place N queens on an N x N board so that no two share a row, column or diagonal. Backtracking places one queen per row and prunes any column/diagonal that is already attacked.

In short: Put a queen row by row; if a row has no safe square, go back and move the previous queen.

N-Queens: place with no shared row/col/diag

Think about it

The canonical constraint-satisfaction example; interviewers test diagonal indexing and pruning.

Row index r, column c: column conflict set cols, main diagonal id r - c (constant along a diagonal), anti-diagonal id r + c.

Checking safety is O(1) with three sets (or bitmasks).

Brute force over all placements is N^N; one queen per row gives N!

; pruning reduces dramatically (about 15,000 nodes for N=8).

Number of solutions: N=4 gives 2, N=6 gives 4, N=8 gives 92 (12 distinct up to symmetry), N=1 gives 1, N=2 and N=3 give 0.

Time still exponential, roughly O(N!

) worst case; space O(N) for the recursion and sets.

Bitmask version uses integers for cols, d1, d2 with lowest-set-bit extraction (bits = avail & -avail) and is the fastest.

Symmetry can halve search (place the first row only in the left half).

Same pattern solves Sudoku (row/col/box sets) and word search; backtracking vs DP: use DP when subproblems overlap, backtracking when you must enumerate or constraints are irregular.

Key points

  • Diagonal id: r - c for ones going down-right, r + c for down-left.
  • Constraint propagation: Eliminating options early based on constraints.

Example

Code
N-Queens (sets and bitmask):
def solve_n_queens(n):
    cols, d1, d2 = set(), set(), set()
    board, res = [-1] * n, []
    def place(r):
        if r == n:
            res.append(['.' * c + 'Q' + '.' * (n - c - 1) for c in board])
            return
        for c in range(n):
            if c in cols or (r - c) in d1 or (r + c) in d2:
                continue
            cols.add(c); d1.add(r - c); d2.add(r + c); board[r] = c
            place(r + 1)
            cols.remove(c); d1.remove(r - c); d2.remove(r + c)   # unchoose
    place(0)
    return res

def count_queens_bits(n):                  # bitmask, fastest
    full = (1 << n) - 1
    def go(cols, d1, d2):
        if cols == full: return 1
        total, avail = 0, full & ~(cols | d1 | d2)
        while avail:
            bit = avail & -avail
            avail ^= bit
            total += go(cols | bit, ((d1 | bit) << 1) & full, (d2 | bit) >> 1)
        return total
    return go(0, 0, 0)

Solved examples

Example 01 · Basic

What does f(4) return? def f(n): return 1 if n <= 1 else f(n-1) + f(n-2)

Given Data:
    Required To Find:

    Value and number of calls

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: f(1)=1, f(0)=1 (n<=1).
    Step 2: f(2)=2, f(3)=3, f(4)=5.
    Step 3: Calls: C(n)=C(n-1)+C(n-2)+1: C(0)=C(1)=1, C(2)=3, C(3)=5, C(4)=9.
    Final Answer: f(4)=5 with 9 calls

    Approach note: Count nodes in the tree for call counts.

    Example 02 · Intermediate

    List subsets of [1,2,2] without duplicates.

    Given Data:
      Required To Find:

      All unique subsets

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Sorted [1,2,2].
      Step 2: At level start=1, index 2 equals index 1 and i > start, so skipped.
      Step 3: Result: [], [1], [1,2], [1,2,2], [2], [2,2].
      Final Answer: 6 subsets

      Approach note: Skip only when i > start, not just i > 0.

      Example 03 · Advanced

      For N=4, queen in row 0 at col 1. Show the forced placement and result.

      Given Data:
        Required To Find:

        Solution

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Row 0 col 1 blocks col 1, diagonals r-c=-1, r+c=1.
        Step 2: Row 1: col 0 has r+c=1 (blocked anti-diagonal), col 1 is blocked, col 2 has r-c=-1 (blocked diagonal), so only col 3 is safe.
        Step 3: Row 2: blocked cols {1,3}, anti-diagonals {1,4}; col 2 has r+c=4 blocked, so only col 0 is safe.
        Step 4: Row 3: col 2 is the only safe cell (r-c=1, r+c=5 are free).
        Final Answer: Board [1,3,0,2] (one of two solutions; the other is [2,0,3,1])

        Approach note: Diagonal ids make conflict checks O(1).

        Example 04 · Basic

        Compute factorial(5) recursively. How many call frames peak on the stack?

        Given Data:
          Required To Find:

          Value and peak depth

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: 5! = 5*4*3*2*1 = 120
          Step 2: Calls: f(5)…f(1) then base
          Step 3: Peak frames ≈ 5 for n down to 1
          Final Answer: 120; peak depth 5 frames for n down to 1

          Approach note: Naive recursion uses O(n) stack space.

          Real-world applications

          DSA

          Using Recursion & Backtracking in real projects

          Sudoku solvers, constraint satisfaction, path finding in mazes, generating test cases, parsing.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: Backtracking and brute force are the same.

          Why this is wrong: Brute force enumerates every full candidate; backtracking abandons partial candidates as soon as constraints fail.

          ✅ Verified Truth: Pruning cuts the exponential tree dramatically though worst case remains exponential.

          ⚠️ Exam Tip: Mention pruning when asked for the difference.

          ❌ Myth: Appending path to results is enough.

          Why this is wrong: path is mutated later, so stored references end up empty or identical.

          ✅ Verified Truth: Append path[:] or list(path).

          ⚠️ Exam Tip: Classic bug in subsets/permutations code.

          ❌ Myth: Recursion is always slower and should be avoided.

          Why this is wrong: Recursion is natural for trees and divide and conquer; cost is stack depth, not time.

          ✅ Verified Truth: Choose recursion for clarity, iteration for very deep inputs.

          ⚠️ Exam Tip: Know the recursion limit.

          Revision notes

          Recursion solves a problem by reducing it to smaller instances of itself with a base case. Backtracking builds candidates incrementally, abandons (prunes) branches that cannot succeed, and undoes choices to explore alternatives.

          High-Yield Quick Revision Points

          1. Base case + progress + combine; depth = stack space
          2. Naive Fibonacci O(phi^n); memoize -> O(n); Hanoi 2^n - 1
          3. Backtrack: choose, explore, unchoose; copy path; prune
          4. Duplicates: sort, skip a[i]==a[i-1] when i > start
          5. N-Queens: cols, r-c, r+c sets; N=8 -> 92 solutions

          Practice questions

          Question 1 · MCQ (GATE)

          Number of subsets of an n-element set:

          Question 2 · MCQ (GATE)

          Tower of Hanoi minimum moves for n disks:

          Question 3 · MCQ (Interview)

          Number of solutions to 8-Queens:

          Question 4 · MCQ (Interview)

          Cells on the same anti-diagonal share:

          Question 5 · MCQ (Interview)

          power(x, n) calling power(x, n//2) twice runs in: