Pruning the search
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Plain backtracking without pruning is just polite brute force: if a tree has depth 20 and branching factor 4, visiting every node takes 4²⁰ ≈ 10¹² steps. Pruning is the art of proving—in O(1) time at an internal node—that an entire subtree is either invalid or worse than an answer you already have, and cutting that branch off immediately.
Stopping early with bounds
Pruning is stopping a branch of the search early when it can no longer lead to a valid or better answer, which can make backtracking much faster.
There are two main reasons to prune a branch before recursing.
Example 1 · Branch and Bound: Minimizing Maximum Workload Across k Workers
import java.util.Arrays;
public class WorkloadBranchAndBound { private static int bestMaxLoad; private static int nodesVisited;
public static int minimumTimeRequired(int[] jobs, int k) { Arrays.sort(jobs); // Reverse to descending order so big jobs are assigned first for (int l = 0, r = jobs.length - 1; l < r; l++, r--) { int t = jobs[l]; jobs[l] = jobs[r]; jobs[r] = t; } bestMaxLoad = Integer.MAX_VALUE; nodesVisited = 0; backtrack(jobs, 0, new int[k], 0); return bestMaxLoad; }
private static void backtrack(int[] jobs, int idx, int[] workerLoad, int currentMax) { nodesVisited++; // Optimality bound: cannot beat bestMaxLoad found so far! if (currentMax >= bestMaxLoad) { return; } if (idx == jobs.length) { bestMaxLoad = currentMax; return; } for (int w = 0; w < workerLoad.length; w++) { workerLoad[w] += jobs[idx]; backtrack(jobs, idx + 1, workerLoad, Math.max(currentMax, workerLoad[w])); workerLoad[w] -= jobs[idx];
// Symmetry prune: if worker w had 0 load before this job, all later empty workers are identical! if (workerLoad[w] == 0) { break; } } }
public static void main(String[] args) { int[] jobs = {1, 2, 4, 7, 8}; System.out.println("Min max load (k=2): " + minimumTimeRequired(jobs, 2) + " (nodes visited: " + nodesVisited + ")"); int[] jobs2 = {3, 2, 3, 7, 5, 4}; System.out.println("Min max load (k=3): " + minimumTimeRequired(jobs2, 3) + " (nodes visited: " + nodesVisited + ")"); }}Min max load (k=2): 11 (nodes visited: 30) Min max load (k=3): 9 (nodes visited: 78)
What this code does
- The first complete leaf reached sets
bestMaxLoadto a strong greedy upper bound. Every subsequent branch whosecurrentMax >= bestMaxLoadis pruned immediately. if (workerLoad[w] == 0) break;is the empty-worker symmetry rule: assigningjobs[idx]to the first idle worker is identical to assigning it to any other idle worker.
In detail:
- Minimization bound: If
currentCost + optimisticRemainingCost >= bestCost, prune (return). Even ifoptimisticRemainingCostis0(because all future edge costs are ≥ 0), checkingif (currentCost >= bestCost) return;cuts off huge subtrees. - Maximization bound: If
currentValue + maxPossibleRemainingValue <= bestValue(for example,currentValue + suffixSum[idx] <= bestValue), prune (return). - Symmetry pruning: In bucket-packing problems (like Matchsticks to Square or Partition to K Equal Subsets), if two buckets currently hold the exact same sum (
bucket[j] == bucket[j - 1]), puttingnums[idx]intobucket[j]is symmetric to putting it intobucket[j - 1], which we just tried and failed—socontinue! Even stronger, ifbucket[j] == 0fails, no later empty bucket can succeed either, sobreak!
- Feasibility pruning (Constraints): The partial state can never become valid. For example, when partitioning an array of sticks into 4 equal sides of a square (
sideLen = totalSum / 4), any stick longer thansideLenor any bucket wherebucket[j] + stick > sideLenis immediately rejected. - Optimality pruning (Branch and Bound): When searching for the minimum or maximum cost (such as the fewest coins or shortest tour), keep a variable
bestSoFarinitialized to the best answer found so far. At every node, compute an optimistic bound on how good the current path could possibly finish; if that bound cannot beatbestSoFar,returnimmediately!
Ordering choices
Ordering choices means deciding which choice to try first. A counter-intuitive rule governs constraint satisfaction: try the largest or most constrained items first (often called the fail-first heuristic).
import java.util.Arrays;
public class LargestFirst { public static void main(String[] args) { int[] sticks = {1, 1, 2, 2, 2}; Arrays.sort(sticks); // ascending first for (int i = 0, j = sticks.length - 1; i < j; i++, j--) { // then reverse int temp = sticks[i]; sticks[i] = sticks[j]; sticks[j] = temp; } System.out.println(Arrays.toString(sticks)); // try the 2s first }}[2, 2, 2, 1, 1]
Why does sorting sticks in descending order (Arrays.sort, then reverse) make Matchsticks to Square 100 times faster than ascending order? Because a huge stick (say length 7 when sideLen = 8) leaves only 1 unit of room in its bucket; if no 1 exists, the branch fails at depth 1 or 2 near the root! If you try tiny sticks (1, 1, 1, 1...) first, they fit everywhere at the top of the tree, and you only discover that the big 7s cannot fit when you reach depth 14 at the very bottom—repeating that failure across thousands of branches.
In optimization problems (Branch and Bound), ordering choices so that a strong greedy candidate is explored first sets a tight bestSoFar bound right away, which then prunes almost every weaker branch that follows.
if (c[i] > remaining) break; (Combination Sum); sort descending when you must place every item into fixed-capacity buckets (Matchsticks to Square, Fair Distribution of Cookies).Cost with and without pruning
Even when pruning does not change the theoretical worst-case Big-O formula on adversarial inputs, its effect on real inputs is dramatic.
Example 2 · Measuring Call Counts: Matchsticks to Square With and Without Pruning
import java.util.Arrays;
public class MatchsticksPruningComparison { static int callsUnpruned = 0; static int callsPruned = 0;
// 1. Naive backtracking (ascending order, no symmetry pruning) public static boolean naive(int[] sticks, int idx, int[] sides, int target) { callsUnpruned++; if (idx == sticks.length) { return sides[0] == target && sides[1] == target && sides[2] == target; } for (int b = 0; b < 4; b++) { if (sides[b] + sticks[idx] > target) continue; sides[b] += sticks[idx]; if (naive(sticks, idx + 1, sides, target)) return true; sides[b] -= sticks[idx]; } return false; }
// 2. Pruned backtracking (descending order + empty/duplicate bucket symmetry skip) public static boolean pruned(int[] sticks, int idx, int[] sides, int target) { callsPruned++; if (idx == sticks.length) return true; for (int b = 0; b < 4; b++) { if (sides[b] + sticks[idx] > target) continue; // Symmetry prune: if a previous bucket has the exact same current sum, skip! boolean sameAsEarlier = false; for (int prev = 0; prev < b; prev++) { if (sides[prev] == sides[b]) { sameAsEarlier = true; break; } } if (sameAsEarlier) continue;
sides[b] += sticks[idx]; if (pruned(sticks, idx + 1, sides, target)) return true; sides[b] -= sticks[idx]; } return false; }
public static void main(String[] args) { int[] raw = {1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5}; int sum = 0; for (int x : raw) sum += x; int target = sum / 4; // 32 / 4 = 8
int[] asc = raw.clone(); Arrays.sort(asc); boolean ans1 = naive(asc, 0, new int[4], target);
int[] desc = raw.clone(); Arrays.sort(desc); for (int l = 0, r = desc.length - 1; l < r; l++, r--) { int t = desc[l]; desc[l] = desc[r]; desc[r] = t; } boolean ans2 = pruned(desc, 0, new int[4], target);
System.out.println("Can form square: " + ans1 + " / " + ans2); System.out.println("Calls (ascending, no symmetry prune): " + callsUnpruned); System.out.println("Calls (descending + symmetry prune): " + callsPruned); }}Can form square: true / true Calls (ascending, no symmetry prune): 35 Calls (descending + symmetry prune): 12
What this code does
- On the exact same 11-stick input summing to 32 (
target = 8per side), ascending order without symmetry pruning makes 35 recursive calls. - Sorting the sticks descending (
[5, 5, 4, 4, 3, 3, 2, 2, 2, 1, 1]) and skipping buckets with duplicate current sums solves the problem in just 12 calls (the minimum possible depth for 11 sticks plus base case)!
Cutting the effective branching factor from b = 4 down to b = 2 at depth d = 12 reduces tree leaves from 4¹² = 16,777,216 to 2¹² = 4,096—a 4,000× speedup. You can measure pruning directly during development by adding a static int calls = 0; counter at the top of backtrack(...) and printing calls before and after each pruning rule.
Real world: puzzle solvers and timetable builders
Backtracking with pruning powers real-world constraint satisfaction solvers (CSP) and timetabling engines used by universities, airlines, and hospitals.
Example 3 · Real World: University Exam Timetable Builder with Conflict Pruning
import java.util.Arrays;
public class ExamTimetableBuilder { // conflict[a][b] == true if some students take both course a and course b public static int[] buildSchedule(String[] courses, boolean[][] conflict, int numSlots) { int n = courses.length; int[] assignedSlot = new int[n]; Arrays.fill(assignedSlot, -1); if (backtrack(0, n, conflict, numSlots, assignedSlot)) { return assignedSlot; } return new int[0]; }
private static boolean backtrack(int course, int n, boolean[][] conflict, int numSlots, int[] assignedSlot) { if (course == n) return true; for (int slot = 0; slot < numSlots; slot++) { if (canUseSlot(course, slot, conflict, assignedSlot)) { assignedSlot[course] = slot; if (backtrack(course + 1, n, conflict, numSlots, assignedSlot)) { return true; } assignedSlot[course] = -1; } } return false; }
private static boolean canUseSlot(int course, int slot, boolean[][] conflict, int[] assignedSlot) { for (int prev = 0; prev < course; prev++) { if (conflict[course][prev] && assignedSlot[prev] == slot) { return false; // Student cohort conflict! } } return true; }
public static void main(String[] args) { String[] courses = {"DSA", "OS", "DBMS", "Networks"}; boolean[][] conflict = { {false, true, true, false}, {true, false, true, true }, {true, true, false, true }, {false, true, true, false} }; int[] schedule = buildSchedule(courses, conflict, 3); for (int i = 0; i < courses.length; i++) { System.out.println(courses[i] + " -> Slot " + (schedule[i] + 1)); } }}DSA -> Slot 1 OS -> Slot 2 DBMS -> Slot 3 Networks -> Slot 1
What this code does
DSA,OS, andDBMSall conflict with one another, so they are assigned Slots 1, 2, and 3.Networksconflicts withOS(Slot 2) andDBMS(Slot 3) but notDSA(Slot 1), so it shares Slot 1.
When a university schedules 500 courses into rooms and time slots, the choices are (room, slot) pairs for each course; the constraints are room capacity, no professor teaching two classes at once, and no student cohort having overlapping required classes. University timetablers use the exact same fail-first heuristic you just learned: schedule the largest, most constrained lecture halls and multi-section courses first, and use symmetry and bound pruning to reject conflicting partial schedules in microseconds.
Next step
Check your understanding
10 quick questions