Knowledge / Computer Science and Engineering / Recursion and backtracking

Recursion and backtracking

Computer Science and Engineering (B.E./B.Tech) · Algorithms · free study notes for exams, placements and interviews

In short

Recursion is a problem-solving technique in which a function calls itself on a smaller instance of the same problem until it reaches a base case that can be answered directly. Backtracking is recursion applied to search: it builds a candidate solution one choice at a time, abandons ("backtracks" from) any partial candidate that cannot possibly lead to a valid solution, and so explores a pruned state-space tree instead of all combinations. Together they are the foundation of N-Queens, Sudoku, maze solving, subset and permutation generation, and are the single most common technique family in placement coding rounds (TCS NQT, Infosys HackWithInfy, Wipro, Zoho, Amazon, Microsoft, Flipkart, Oracle, Adobe) and in GATE CS questions on recurrences and call-stack behaviour. University syllabi (AICTE model curriculum, UGC CBCS "Data Structures" and "Design and Analysis of Algorithms") examine recursion tracing, recurrence formulation, stack space and the standard backtracking algorithms with their complexities.

Explained

Anatomy of a recursive function

Classification of recursion

Recursion versus iteration, and conversion

Backtracking: the method

void solve(partial P):
    if P is a complete solution:  record(P); return
    for each candidate c in choices(P):
        if isSafe(P, c):            # feasibility / bounding function
            place c in P            # choose
            solve(P)                # explore
            remove c from P         # un-choose (backtrack)

Design decisions that make or break a backtracking solution

Backtracking compared with related techniques

The standard problem set examined

Key points

Formulas and examples

Recursive algorithm = base case(s) + recursive case(s) on a strictly smaller input
Auxiliary space = (maximum recursion depth) × (size of one stack frame, in bytes)
T(n) = T(n−1) + O(1) → O(n) — linear recursion (factorial, array sum)
T(n) = 2T(n−1) + O(1) → O(2ⁿ) — tree recursion (Hanoi, include/exclude subsets)
T(n) = T(n−1) + T(n−2) + O(1) → O(φⁿ), φ = (1+√5)/2 ≈ 1.618 — naive Fibonacci
T(n) = n·T(n−1) + O(n) → O(n!) — permutation generation
Hanoi moves: M(n) = 2M(n−1) + 1, M(1) = 1 → M(n) = 2ⁿ − 1
Number of subsets of n elements = 2ⁿ; nodes in the include/exclude tree = 2ⁿ⁺¹ − 1
Permutations of n distinct items = n!; k-combinations C(n,k) = n! / (k!(n−k)!)
Naive Fibonacci call count: C(n) = 2·F(n+1) − 1, with F(1) = F(2) = 1
Backtracking cost ≈ (nodes in the pruned state-space tree) × (cost of one feasibility check)
N-Queens row-wise search space = nⁿ sequences, reduced to n! by the column constraint alone

(All quantities here are counts — dimensionless; space figures are in bytes/KB/MB, times in seconds at an assumed machine rate.)

Example 1 - Towers of Hanoi, n = 4.

Example 2 - cost of naive recursion: Fibonacci.

Example 3 - 4-Queens traced by hand (row by row, columns 0-3).

StepBoard stateAction
1Q at (0,0)place
2(1,0) same column, (1,1) diagonal → (1,2)place
3row 2: (2,0) column, (2,1) diagonal, (2,2) column, (2,3) diagonalall fail → backtrack
4retry row 1 at (1,3)place
5(2,1) safeplace
6row 3: (3,0) col, (3,1) col, (3,2) diag from (2,1), (3,3) colfail → rows 2 and 1 exhausted, backtrack to row 0
7row 0 moved to (0,1); then (1,3), (2,0), (3,2)solution [1,3,0,2]
8continue the searchsecond solution [2,0,3,1]
bool place(int r,int n){
  if(r==n){ count++; return false; }          // false = keep searching for all solutions
  for(int c=0;c<n;c++){
    int d1=r+c, d2=r-c+n-1;
    if(col[c]||diag1[d1]||diag2[d2]) continue;
    col[c]=diag1[d1]=diag2[d2]=1; pos[r]=c;   // choose
    place(r+1,n);                              // explore
    col[c]=diag1[d1]=diag2[d2]=0;              // un-choose
  }
  return false;
}

Example 4 - subset sum with pruning. Set S = {3, 34, 4, 12, 5, 2}, target T = 9.

Example 5 - stack space and overflow. A recursive sum(1..n) whose frame is about 64 bytes (two ints, saved base pointer, return address, padding).

ProblemTime (worst case)Aux. spaceOutput size
Factorial / array sumO(n)O(n) stack1 value
Towers of HanoiO(2ⁿ)O(n)2ⁿ − 1 moves
All subsetsO(2ⁿ · n)O(n)2ⁿ subsets
All permutationsO(n! · n)O(n)n! permutations
N-Queens (all solutions)O(n!)O(n)92 for n = 8
Sudoku 9×9O(9m), m = blanksO(m)1 grid
Rat in a maze (n×n)O(4n²)O(n²)all paths
Graph m-colouringO(mⁿ)O(n)colour vector
Hamiltonian cycleO(n!)O(n)one cycle

Where it is used

Interview questions

Common mistakes

Related topics

Time and space complexity · Divide and conquer · Dynamic programming · Graph algorithms: BFS, DFS and shortest paths · Greedy algorithms · DSA interview patterns

Open in the Knowledge reader →Find jobs →