InterviewSam
Tech TracksStudySystem DesignAptitudeDaily Quiz
Log inStart free
Tech TracksStudySystem DesignAptitudeDaily Quiz
All topics

Backtracking

Build candidates step by step and undo choices: subsets, permutations, puzzles.

6 pages, free to read

Start studying
  1. 1

    The backtracking template

    Intermediate

    Backtracking builds a solution one choice at a time, explores each choice with recursion, and undoes it before trying the next, so it can search every valid answer without storing them all.

    10 min read
  2. 2

    Subsets

    Intermediate

    To list every subset, decide for each element whether it is in or out; a set of n elements has 2^n subsets, and backtracking generates them in O(n * 2^n).

    9 min read
  3. 3

    Permutations

    Intermediate

    A permutation is an ordering of all the elements; n distinct elements have n! orderings, and backtracking builds them position by position using a used array.

    9 min read
  4. 4

    Combinations & combination sum

    Intermediate

    Combination problems pick unordered groups that meet a rule such as size k or a target sum; the start index prevents reordered duplicates, and a running remainder lets you stop early.

    10 min read
  5. 5

    Constraint puzzles (N-Queens, Sudoku)

    Advanced

    Constraint puzzles fill a board one cell or row at a time, check the rules before each placement using fast lookup sets, and backtrack the moment a rule would be broken.

    12 min read
  6. 6

    Pruning the search

    Advanced

    Pruning cuts off branches of the search tree that cannot lead to a valid or better answer, which is what makes exponential backtracking fast enough in practice.

    10 min read