Recursion & Backtracking

Problems Article MCQs

Recursion & Backtracking — Complete Step-by-Step Guide

Module 8 — Recursion & Backtracking: Recursion, the call stack, divide and conquer, and backtracking Structured as Topic → Plain-English Explanation → Real Code → Visual Diagram → Complexity → Common Pitfalls.


1. Recursion & The Call Stack

A function is recursive when it calls itself to solve a smaller version of the same problem. Every recursive function needs a base case — a condition where it stops calling itself and returns directly — otherwise it would call itself forever. Each call adds a new frame to the call stack; once the base case is hit, the calls "unwind," each frame returning its result to the one that called it.

int factorial(int n) {
    if (n <= 1) return 1;          // base case
    return n * factorial(n - 1);   // recursive case
}
factorial(4) factorial(3) factorial(2) factorial(1) = 1 returns unwind:
1 → 2 → 6 → 24
Figure 8.1 — Calls go down the stack; results unwind back up
Common Pitfall: A missing or incorrect base case causes infinite recursion, which eventually crashes the program with a stack overflow once memory for call frames runs out.

2. Divide and Conquer

Divide and conquer is a recursive strategy with three steps:

  1. Divide: Split the problem into smaller subproblems of the same type.
  2. Conquer: Solve each subproblem recursively (until a base case is trivial to solve directly).
  3. Combine: Merge the subproblem results into the final answer.

Merge sort (Module 5) is the textbook example: divide the array in half, sort each half recursively, then merge the sorted halves.


3. Backtracking

Backtracking is a refinement of recursion for exploring all possible choices to a problem: it builds a solution incrementally, and the moment it discovers the current partial solution can't possibly lead to a valid answer, it backtracks — undoes the last choice and tries a different one — rather than exploring every possibility to the end. This pruning is what makes backtracking far faster than brute force for problems like N-Queens, Sudoku, and generating permutations.

void permute(vector<int>& nums, vector<int>& current, vector<bool>& used) {
    if (current.size() == nums.size()) { 
        /* record solution */ 
        return; 
    }
    for (int i = 0; i < nums.size(); i++) {
        if (used[i]) continue;
        used[i] = true;
        current.push_back(nums[i]);
        permute(nums, current, used); // choose
        current.pop_back();            // un-choose (backtrack)
        used[i] = false;
    }
}
[ ] [1] [2] [3] [1,2,3] dead-end a dead-end path is abandoned — backtrack and try the next choice
Figure 8.2 — Backtracking explores choices and undoes dead ends
Practice Recursion & Backtracking MCQs
Master Recursion & Backtracking concepts with timed, competitive MCQs with detailed explanations.
Start Topic Quiz →
Yukti Mascot