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.
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
// 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);
} def construct(grid): # quad tree
def build(r, c, size):
if size == 1:
return Node(grid[r][c] == 1, True, None, None, None, None)
h = size // 2
kids = [build(r, c, h), build(r, c + h, h), build(r + h, c, h), build(r + h, c + h, h)]
if all(k.isLeaf for k in kids) and len({k.val for k in kids}) == 1:
return Node(kids[0].val, True, None, None, None, None) # combine: one leaf
return Node(True, False, *kids)
return build(0, 0, len(grid))
def make_largest_special(s): # split into blocks, fix each, sort
parts, bal, start = [], 0, 0
for i, ch in enumerate(s):
bal += 1 if ch == '1' else -1
if bal == 0: # s[start..i] is "1" + inner + "0"
parts.append('1' + make_largest_special(s[start + 1:i]) + '0')
start = i + 1
return ''.join(sorted(parts, reverse=True)) // quad tree: build the four quadrants, then merge them if they are equal leaves
Node* build(vector<vector<int>>& g, int r, int c, int size) {
if (size == 1) return new Node(g[r][c] == 1, true);
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);
bool allLeaves = tl->isLeaf && tr->isLeaf && bl->isLeaf && br->isLeaf;
if (allLeaves && tl->val == tr->val && tr->val == bl->val && bl->val == br->val) {
bool v = tl->val;
delete tl; delete tr; delete bl; delete br;
return new Node(v, true); // combine: one leaf
}
return new Node(true, false, tl, tr, bl, br);
}
Node* construct(vector<vector<int>>& grid) { return build(grid, 0, 0, grid.size()); }
// special binary string: split into top-level blocks, fix each inside, sort the blocks
string makeLargestSpecial(string s) {
vector<string> parts;
int bal = 0, start = 0;
for (int i = 0; i < (int)s.size(); i++) {
bal += s[i] == '1' ? 1 : -1;
if (bal == 0) { // s[start..i] is "1" + inner + "0"
parts.push_back("1" + makeLargestSpecial(s.substr(start + 1, i - start - 1)) + "0");
start = i + 1;
}
}
sort(parts.rbegin(), parts.rend()); // biggest block first
string res;
for (auto& p : parts) res += p;
return res;
} // quad tree: build the four quadrants, then merge them if they are equal leaves
function construct(grid) {
function build(r, c, size) {
if (size === 1) return new _Node(grid[r][c] === 1, true, null, null, null, null);
const h = size / 2;
const kids = [build(r, c, h), build(r, c + h, h), build(r + h, c, h), build(r + h, c + h, h)];
if (kids.every(k => k.isLeaf && k.val === kids[0].val))
return new _Node(kids[0].val, true, null, null, null, null); // combine: one leaf
return new _Node(true, false, ...kids);
}
return build(0, 0, grid.length);
}
// special binary string: split into top-level blocks, fix each inside, sort the blocks
function makeLargestSpecial(s) {
const parts = [];
let bal = 0, start = 0;
for (let i = 0; i < s.length; i++) {
bal += s[i] === '1' ? 1 : -1;
if (bal === 0) { // s[start..i] is "1" + inner + "0"
parts.push('1' + makeLargestSpecial(s.slice(start + 1, i)) + '0');
start = i + 1;
}
}
return parts.sort().reverse().join(''); // biggest block first
} The variations
-
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.
-
2Split into balanced blocks and reorder
A running balance of
+1for1and-1for0returns 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
1and0). - Copying sub-grids or substrings at every level when indexes would do: it adds memory and time.
Lesson done
Next: Digit-by-digit construction →Mark it done once you can write the template from memory and you have solved the worked examples yourself.