Not every problem can be solved quickly. Backtracking is the standard way to search a large space while pruning hopeless branches.

Why Algorithms Have Limits

Algorithms have limits of three kinds. Some problems are unsolvable: no algorithm exists at all, the best-known example being the halting problem. Some are solvable only at a cost that grows exponentially, so that even the fastest computer cannot solve moderately large instances. Others have efficient algorithms, but only up to a proven lower bound, such as Ω(n log n) for comparison sorting. This unit concerns the second kind: problems for which only exponential methods are known, such as finding a Hamiltonian circuit or the best subset of items.

The Backtracking Idea

Backtracking builds a solution one component at a time and checks after each step whether the partial solution can still lead to a complete valid one. If not, the algorithm backtracks: it undoes the last choice and tries the next alternative. It is a systematic, depth-first search of the state-space tree, in which the root is the empty solution, each node is a partial solution, and children extend the parent by one more choice. A node that cannot lead to a solution is non-promising and is pruned: its whole subtree is never explored. This makes backtracking much faster in practice than brute force, which would test every one of the leaves.

Definition: Backtracking. A depth-first search technique that builds a solution incrementally and abandons (prunes) a partial solution as soon as it violates the constraints, then returns to try other choices.

Constraints and the General Scheme

Two kinds of constraint are used. Explicit constraints state which values each component may take (for example a queen's column from 1 to n). Implicit constraints state how the components must relate (no two queens attack each other). A bounding function tests whether a partial solution is still promising. The scheme is: for the current level, try each allowed value; if it satisfies the bounding function, place it and recurse to the next level; if the recursion fails, remove the value and try the next; if no value works, return failure to the previous level. A solution is recorded when all components are filled. For optimisation problems a branch and bound bound on the best value so far also prunes.

Cost of Backtracking

In the worst case no pruning happens and the algorithm visits the entire tree, which is exponential, such as O(2ⁿ) or O(n!). Backtracking therefore does not improve the worst-case complexity, but with good pruning it solves many instances of useful size. The quality of the bounding function decides how much is saved.

Table 4.1: Brute force versus backtracking

Basis Brute force Backtracking
Search Generate all complete candidates Extend partial solutions
Testing After the candidate is complete After every step
Pruning None Cuts non-promising subtrees
Worst case Exponential Exponential
Typical Very slow Much faster

Problem: Choose one number from each of {1, 2}, {3, 4}, {5, 6} so that the total is at most 10. Count the nodes visited with pruning, against the 15 nodes of the full tree.

Solution:

  1. Level 1: both 1 and 2 are promising (2 nodes).
  2. Level 2: 1+3 = 4, 1+4 = 5, 2+3 = 5, 2+4 = 6 are all within 10 (4 nodes).
  3. Level 3: 4+5 = 9 and 4+6 = 10 are accepted; 5+5 = 10 accepted and 5+6 = 11 pruned; 5+5 = 10 accepted and 5+6 pruned; 6+5 = 11 and 6+6 = 12 pruned. Only 4 nodes are entered.
  4. Nodes visited: 1 (root) + 2 + 4 + 4 = 11 instead of 15.

Result: Four solutions (sums 9, 10, 10, 10) found while 4 nodes are never entered.

def search(level, total, sets, limit, stats):
    stats[0] += 1
    if level == len(sets):
        return 1
    n = 0
    for x in sets[level]:
        if total + x <= limit:
            n += search(level + 1, total + x, sets, limit, stats)
    return n
st = [0]
sets = [(1, 2), (3, 4), (5, 6)]
print("solutions with limit 10:", search(0, 0, sets, 10, st))
print("nodes visited:", st[0], "of 15")
st = [0]
print("solutions with limit 8:", search(0, 0, sets, 8, st))

Output

solutions with limit 10: 4
nodes visited: 11 of 15
solutions with limit 8: 0

Common mistakes

  • Treating backtracking as a way to get a polynomial-time algorithm.
  • Using a weak bounding function that prunes almost nothing.
  • Forgetting to undo (reset) a choice before trying the next alternative.
  • Confusing backtracking, which tests partial solutions, with brute force, which tests only full ones.

Key takeaways

  • Backtracking is depth-first search of the state-space tree with pruning of non-promising nodes.
  • Explicit constraints give the range of values; implicit constraints relate them.
  • It does not improve the worst case, but often works well in practice.
  • On failure, undo the last choice and try the next.

Practice questions

  1. What is a non-promising node?
  2. Distinguish explicit and implicit constraints.
  3. Does backtracking beat brute force in the worst case?

Answers to the practice questions

  1. A partial solution that cannot be extended to a valid complete solution, so its subtree is pruned.
  2. Explicit constraints give the allowed values of each component; implicit constraints say how components must relate.
  3. No, both are exponential in the worst case, but backtracking prunes in practice.

Sources

  • Official BCA syllabus Design and Analysis of Algorithms, course code 26BCA404DS03, Unit IV