Chapter 08
Recursion & Backtracking
3 topics · 2 sections · beginner-friendly study notes · Updated
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.
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.

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.
Read more
Example
CodeRecursion 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)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.
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
CodeBacktracking 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 resN-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.
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.
Read more
Example
CodeN-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
What does f(4) return? def f(n): return 1 if n <= 1 else f(n-1) + f(n-2)
Value and number of calls
Formula Applied:—Approach note: Count nodes in the tree for call counts.
List subsets of [1,2,2] without duplicates.
All unique subsets
Formula Applied:—Approach note: Skip only when i > start, not just i > 0.
For N=4, queen in row 0 at col 1. Show the forced placement and result.
Solution
Formula Applied:—Approach note: Diagonal ids make conflict checks O(1).
Compute factorial(5) recursively. How many call frames peak on the stack?
Value and peak depth
Formula Applied:—Approach note: Naive recursion uses O(n) stack space.
Real-world applications
Using Recursion & Backtracking in real projects
Sudoku solvers, constraint satisfaction, path finding in mazes, generating test cases, parsing.
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
- Base case + progress + combine; depth = stack space
- Naive Fibonacci O(phi^n); memoize -> O(n); Hanoi 2^n - 1
- Backtrack: choose, explore, unchoose; copy path; prune
- Duplicates: sort, skip a[i]==a[i-1] when i > start
- N-Queens: cols, r-c, r+c sets; N=8 -> 92 solutions
Practice questions
Number of subsets of an n-element set:
Tower of Hanoi minimum moves for n disks:
Number of solutions to 8-Queens:
Cells on the same anti-diagonal share:
power(x, n) calling power(x, n//2) twice runs in: