Recursion & Backtracking · Pattern 7 of 9

Divide and conquer: split, solve, combine

Split the input into independent parts, solve each part recursively, then combine the answers. Unlike backtracking, nothing is undone: each call returns its result to the caller.

2 variations · 2 problems

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • The input splits naturally into halves, quadrants or balanced blocks
  • Each part can be solved without looking at the others
  • The answer for the whole is built from the answers of the parts

The template

Divide and Conquer
// quad tree: build the four quadrants, then merge them if they are equal leaves
Node construct(int[][] grid) { return build(grid, 0, 0, grid.length); }
Node build(int[][] g, int r, int c, int size) {
    if (size == 1) return new Node(g[r][c] == 1, true, null, null, null, null);
    int h = size / 2;
    Node tl = build(g, r, c, h), tr = build(g, r, c + h, h);           // divide
    Node bl = build(g, r + h, c, h), br = build(g, r + h, c + h, h);
    boolean allLeaves = tl.isLeaf && tr.isLeaf && bl.isLeaf && br.isLeaf;
    if (allLeaves && tl.val == tr.val && tr.val == bl.val && bl.val == br.val)
        return new Node(tl.val, true, null, null, null, null);       // combine: one leaf
    return new Node(true, false, tl, tr, bl, br);
}

// special binary string: split into top-level blocks, fix each inside, sort the blocks
String makeLargestSpecial(String s) {
    List<String> parts = new ArrayList<>();
    int bal = 0, start = 0;
    for (int i = 0; i < s.length(); i++) {
        bal += s.charAt(i) == '1' ? 1 : -1;
        if (bal == 0) {                       // s[start..i] is "1" + inner + "0"
            parts.add("1" + makeLargestSpecial(s.substring(start + 1, i)) + "0");
            start = i + 1;
        }
    }
    parts.sort(Collections.reverseOrder()); // biggest block first
    return String.join("", parts);
}

The variations

  1. 1Split a grid into quadrants

    Recurse on the four quarters. When all four come back as leaves with the same value, merge them into one leaf; otherwise the node keeps four children.

  2. 2Split into balanced blocks and reorder

    A running balance of +1 for 1 and -1 for 0 returns to zero at the end of each top-level block. Make each block as large as possible inside, then sort the blocks in decreasing order.

Mistakes to avoid

  • Quad tree: merging four leaves without checking that they all hold the same value.
  • Special binary string: sorting the blocks but forgetting to fix the inside of each block first (recurse on the part between its outer 1 and 0).
  • Copying sub-grids or substrings at every level when indexes would do: it adds memory and time.
Next: Digit-by-digit construction →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.