Codacoda
Back to Academy

patterns

Backtracking

Backtracking systematically explores all possible solutions by building candidates incrementally and abandoning a path as soon as it determines the candidate cannot lead to a valid solution. It uses recursion to try each option, undo the choice (backtrack), and try the next, effectively pruning the search space compared to brute force.

Use Cases

  • Generating all subsets, permutations, and combinations
  • Solving constraint satisfaction problems like Sudoku and N-Queens
  • Finding all paths in a maze or grid

Complexity Analysis

MetricBestAverageWorst
TimeO(n!)O(n!)O(n!)
SpaceO(n)

Visualization

123012
Subsets:[]
Speed:1x
Array: [1, 2, 3]. Generate all subsets using backtracking.Step 1 / 9

Implementation

Output

Click "Run Code" to see output...