Split a problem, solve the halves and combine the answers.
Use it when a problem on n items splits into smaller problems of the same kind, and the answers combine cheaply. Signal words: split in half, solve each half, the answer may cross the middle.
Split choose a middle, or a cut chosen by the data. Make each part smaller.
Solve call the same function on each part. Solve a part once and reuse the answer.
Combine join the answers, and cover what crosses the split.
Cost draw the tree, and add up the levels.
In this lesson you learn to split a problem into smaller problems of the same kind, solve each one, and combine the answers. You learn why the combine step must look across the split, and how to read the cost of the recursion from its tree.
You work on a budgeting app at a bank. The app shows the best streak of a user's history: the run of neighbouring days with the largest total change in balance. A day can add money or take money away.
A first version checks every run. Here is a short test: for 8 days, 3, -4, 5, 2, -1, 2, -6, 4, the best streak is days 3 to 6, with a total of 8.
Your team lead says: Users can pick any history, up to 100,000 days. Is it fast enough?
So the task is this: find the best streak of 100,000 days, and see what it costs.
A steward must count the people in a hall. The steward splits the hall into two halves, and gives each half to an assistant. Each assistant splits again, until a row of one person is counted at once.
Each assistant tells the steward one number, and the steward adds the two. A group sitting across the aisle is a different matter. Neither assistant sees all of it, so the steward must look at the aisle.
The plan has three parts: split, count each part, and combine. The combine part also covers what crosses the split.
A steward counts a hall by halves: each assistant counts one half, and the steward adds the counts and checks the aisle.
Before you write code, try the idea on a small case by hand. Take four days: 3, -4, 5, 2.
Solve it by hand: The best run of four days. The hand-solve sheet loads in your browser.
You split the four days into two halves, and solve each half. Then you look at the runs across the middle.
Each row is one call, in the order the calls start. A call on one day is a leaf. The best run of a call is the largest of three numbers. They are the best run on its left, the best run on its right, and the best run across the middle.
| Call number | Call | Makes | Best run |
|---|---|---|---|
| 1 | days 1 to 4 | days 1 to 2 and days 3 to 4 | 7 |
| 2 | days 1 to 2 | days 1 to 1 and days 2 to 2 | 3 |
| 3 | days 1 | none: a leaf | 3 |
| 4 | days 2 | none: a leaf | -4 |
| 5 | days 3 to 4 | days 3 to 3 and days 4 to 4 | 7 |
| 6 | days 3 | none: a leaf | 5 |
| 7 | days 4 | none: a leaf | 2 |
The best run is days 3 and 4, with a total of 7. The call on all four days made 7 calls.
Start with a correct version. It tries every start and every end, and keeps a running total.
def best_run(values):
best = values[0]
for start in range(len(values)):
total = 0
for end in range(start, len(values)): # every run that begins at start
total += values[end]
best = max(best, total)
return bestThis is correct. The team keeps it as the reference. The question is how long it takes for 100,000 days.
Now check the real size.
A request has a budget of 100 milliseconds, and histories reach 100,000 days.
Run the function on random days, in Python, and look at the numbers:
The budget is a tenth of a second.
Predict the time
Q 4,000 days take about 0.76 seconds. The runs grow with the square of the days. About how long do 40,000 days take?
Answer: B
Ten times the days makes 100 times the runs, so the time grows by about 100. The exact ratio of runs is 99.98.
The first attempt is correct, and it fails the budget by a factor of thousands. The split is the way out.
Look at the calls for the 8 days as a tree. The root is the call on all 8 days. Each call on more than one day splits into two calls on halves. A call on one day is a leaf.
Eight days split into halves: the tree has fifteen calls, and the longest path has four.
The tree has 15 calls: 1 at the top, 2, then 4, then 8 leaves. Each level has twice as many calls on halves of the size. The longest path has 4 calls, so the stack is never deeper than 4.
The count follows from the tree. A tree with n leaves has n - 1 inner nodes, so the calls are 2n - 1. For 1,000 days that is 1,999, and for 100,000 days it is 199,999.
Each call does a fixed amount of work: it adds a few numbers. So the cost is the number of calls, about 2n.
Race: Checks of the first attempt, against the calls of the split. The operation counter loads in your browser.
The race counts the runs of the first attempt by running the double loop, and the calls of the split by running the instrumented template. For 2,000 days the first attempt checks 2,001,000 runs and the split makes 3,999 calls.
The days are 3, -4, 5, 2, -1, 2, -6, 4. The player stops at five steps and asks you to predict.
Dry run: Predict each step: the best run of eight days. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row. Each row is a combine step, in the order the calls close.
| Call | Best run of the left | Best run of the right | Run across the middle | Best run of the call |
|---|---|---|---|---|
| days 1 to 2 | 3 | -4 | -1 | 3 |
| days 3 to 4 | 5 | 2 | 7 | 7 |
| days 1 to 4 | 3 | 7 | 6 | 7 |
| days 5 to 6 | -1 | 2 | 1 | 2 |
| days 7 to 8 | -6 | 4 | -2 | 4 |
| days 5 to 8 | 2 | 4 | 0 | 4 |
| days 1 to 8 | 7 | 4 | 8 | 8 |
The best run of all eight days is 8. It crosses the middle: the best suffix of the left half plus the best prefix of the right half.
The tree of 100,000 days has 199,999 calls, and the stack is only 18 frames deep. The calls decide the time, and the depth decides the memory on the stack. Lesson 2 showed that these are different numbers.
Here is the rule that keeps the answer correct. Every line of the templates exists to protect it.
A divide-and-conquer call splits its problem into smaller problems of the same kind, solves each, and combines the answers, including anything that crosses the split.
The first part is the split: the smaller problems must have the same shape as the whole. The second part is the base case: the smallest problem is answered at once. The third part is the combine step.
The combine step is where most mistakes hide. An answer can use items from both halves. The best run of a range can sit across the middle, so the combine step must look at the items next to the split.
Use it when a problem on n items splits into smaller problems of the same kind, and the answers combine cheaply. Signal words: split in half, solve each half, the answer may cross the middle.
Split: choose a middle, or a cut chosen by the data. Make each part smaller.
Solve: call the same function on each part. Solve a part once and reuse the answer.
Combine: join the answers, and cover what crosses the split.
Cost: draw the tree, and add up the levels.
The simplest case solves one half. The power of an exponent is the square of the power of its half, with one more factor when the exponent is odd. The base is raised to a huge power, and the answer is kept modulo mod. The base must be below mod, so reduce it first; then every product of two figures fits in 64 bits.
def fast_power(base, exp, mod):
# [1] Base case: any base to the power 0 is 1, and a call on 0 makes no further call.
if exp == 0:
return 1 % mod
# [2] Split: solve the half of the exponent once, and keep the answer.
half = fast_power(base, exp // 2, mod)
# [3] Combine: two equal halves make the even part. Reduce by mod so the product fits in 64 bits.
result = half * half % mod
# [4] An odd exponent has one more factor of the base than twice the half.
if exp % 2 == 1:
result = result * base % mod
return resultpublic long fastPower(long base, long exp, long mod) {
// [1] Base case: any base to the power 0 is 1, and a call on 0 makes no further call.
if (exp == 0) {
return 1 % mod;
}
// [2] Split: solve the half of the exponent once, and keep the answer.
long half = fastPower(base, exp / 2, mod);
// [3] Combine: two equal halves make the even part. Reduce by mod so the product fits in 64 bits.
long result = half * half % mod;
// [4] An odd exponent has one more factor of the base than twice the half.
if (exp % 2 == 1) {
result = result * base % mod;
}
return result;
}long long fastPower(long long base, long long exp, long long mod) {
// [1] Base case: any base to the power 0 is 1, and a call on 0 makes no further call.
if (exp == 0) {
return 1 % mod;
}
// [2] Split: solve the half of the exponent once, and keep the answer.
long long half = fastPower(base, exp / 2, mod);
// [3] Combine: two equal halves make the even part. Reduce by mod so the product fits in 64 bits.
long long result = half * half % mod;
// [4] An odd exponent has one more factor of the base than twice the half.
if (exp % 2 == 1) {
result = result * base % mod;
}
return result;
}// Numbers are exact up to 2^53, so use BigInt when mod is above 94,000,000.
function fastPower(base, exp, mod) {
// [1] Base case: any base to the power 0 is 1, and a call on 0 makes no further call.
if (exp === 0) {
return 1 % mod;
}
// [2] Split: solve the half of the exponent once, and keep the answer.
const half = fastPower(base, Math.floor(exp / 2), mod);
// [3] Combine: two equal halves make the even part. Reduce by mod so the product fits in 64 bits.
let result = half * half % mod;
// [4] An odd exponent has one more factor of the base than twice the half.
if (exp % 2 === 1) {
result = result * base % mod;
}
return result;
}Exercise · Put it in order: One half, solved once. Arrange the lines into a fast power that solves the half of the exponent once and keeps the answer modulo mod.
def fast_power(base, exp, mod):
if exp == 0: return 1 % mod
half = fast_power(base, exp // 2, mod)
result = half * half % mod
if exp % 2 == 1: result = result * base % mod
return result
result = half * 2 % mod
half = fast_power(base, exp - 1, mod)Rebuild the template: put its lines back in order. Loads in your browser.
Each call halves the exponent, so an exponent of 1,000,000,000 makes 31 calls. A loop would multiply a billion times. The call solves the half once: that is the whole saving.
Fast power solves the half of the exponent once, squares it, and adds a factor of the base when the exponent is odd.
Exercise · Predict the output: What does each call return?. The function prints `exp:result` as each call is about to return, and the base case returns without printing. What does `fast_power(2, 13, 1000)` print?
def fast_power(base, exp, mod):
if exp == 0:
return 1 % mod
half = fast_power(base, exp // 2, mod)
result = half * half % mod
if exp % 2 == 1:
result = result * base % mod
print(f"{exp}:{result}")
return result
fast_power(2, 13, 1000)Most problems have two halves. The function below returns four numbers for a range: its total, its best prefix, its best suffix and its best run. The best prefix and the best suffix are what the combine step needs.
def best_run(values):
return summarise(values, 0, len(values))[3]
def summarise(values, lo, hi):
# [1] Base case: one day is a run by itself, so its total, prefix, suffix and best run all equal it.
if hi - lo == 1:
return [values[lo], values[lo], values[lo], values[lo]]
# [2] Split: solve the left half and the right half.
mid = (lo + hi) // 2
left = summarise(values, lo, mid)
right = summarise(values, mid, hi)
# [3] Combine: a run across the middle is the best suffix of the left plus the best prefix of the right.
total = left[0] + right[0]
prefix = max(left[1], left[0] + right[1])
suffix = max(right[2], right[0] + left[2])
crossing = left[2] + right[1]
# [4] The best run of the range is the best of the left, the right and the crossing run.
return [total, prefix, suffix, max(left[3], right[3], crossing)]public long bestRun(int[] values) {
return summarise(values, 0, values.length)[3];
}
private long[] summarise(int[] values, int lo, int hi) {
// [1] Base case: one day is a run by itself, so its total, prefix, suffix and best run all equal it.
if (hi - lo == 1) {
return new long[] {values[lo], values[lo], values[lo], values[lo]};
}
// [2] Split: solve the left half and the right half.
int mid = (lo + hi) / 2;
long[] left = summarise(values, lo, mid);
long[] right = summarise(values, mid, hi);
// [3] Combine: a run across the middle is the best suffix of the left plus the best prefix of the right.
long total = left[0] + right[0];
long prefix = Math.max(left[1], left[0] + right[1]);
long suffix = Math.max(right[2], right[0] + left[2]);
long crossing = left[2] + right[1];
// [4] The best run of the range is the best of the left, the right and the crossing run.
return new long[] {total, prefix, suffix, Math.max(Math.max(left[3], right[3]), crossing)};
}vector<long long> summarise(const vector<int>& values, int lo, int hi) {
// [1] Base case: one day is a run by itself, so its total, prefix, suffix and best run all equal it.
if (hi - lo == 1) {
return {values[lo], values[lo], values[lo], values[lo]};
}
// [2] Split: solve the left half and the right half.
int mid = (lo + hi) / 2;
vector<long long> left = summarise(values, lo, mid);
vector<long long> right = summarise(values, mid, hi);
// [3] Combine: a run across the middle is the best suffix of the left plus the best prefix of the right.
long long total = left[0] + right[0];
long long prefix = max(left[1], left[0] + right[1]);
long long suffix = max(right[2], right[0] + left[2]);
long long crossing = left[2] + right[1];
// [4] The best run of the range is the best of the left, the right and the crossing run.
return {total, prefix, suffix, max(max(left[3], right[3]), crossing)};
}
long long bestRun(const vector<int>& values) {
return summarise(values, 0, (int)values.size())[3];
}function summarise(values, lo, hi) {
// [1] Base case: one day is a run by itself, so its total, prefix, suffix and best run all equal it.
if (hi - lo === 1) {
return [values[lo], values[lo], values[lo], values[lo]];
}
// [2] Split: solve the left half and the right half.
const mid = Math.floor((lo + hi) / 2);
const left = summarise(values, lo, mid);
const right = summarise(values, mid, hi);
// [3] Combine: a run across the middle is the best suffix of the left plus the best prefix of the right.
const total = left[0] + right[0];
const prefix = Math.max(left[1], left[0] + right[1]);
const suffix = Math.max(right[2], right[0] + left[2]);
const crossing = left[2] + right[1];
// [4] The best run of the range is the best of the left, the right and the crossing run.
return [total, prefix, suffix, Math.max(left[3], right[3], crossing)];
}
function bestRun(values) {
return summarise(values, 0, values.length)[3];
}The combine step builds a run across the middle from the best suffix of the left and the best prefix of the right. It also keeps the total and the new best prefix and suffix, so the call above can do the same.
The combine step joins the best suffix of the left half to the best prefix of the right half.
Exercise · Find the bug: The prefix that forgets the left half. This best-run search by halves returns a total that is too high on some inputs: it joins days that skip a loss. Which line is wrong?
def best_run(values):
return summarise(values, 0, len(values))[3]
def summarise(values, lo, hi):
if hi - lo == 1:
return [values[lo], values[lo], values[lo], values[lo]]
mid = (lo + hi) // 2
left = summarise(values, lo, mid)
right = summarise(values, mid, hi)
total = left[0] + right[0]
prefix = max(left[1], right[1])
suffix = max(right[2], right[0] + left[2])
crossing = left[2] + right[1]
return [total, prefix, suffix, max(left[3], right[3], crossing)]The cost of a divide-and-conquer recursion depends on how many calls it makes on halves, and how much work each call does. Each row below was measured by running the instrumented function for n = 1,024.
| Recursion on n = 1,024 | Calls | Total work |
|---|---|---|
| One call on a half, constant work | 11 | 11 |
| Two calls on halves, constant work | 2,047 | 2,047 |
| One call on a half, after a scan of n | 11 | 2,047 |
| Two calls on halves, after a scan of n | 2,047 | 11,264 |
The first row has the shape of fast power: a chain of 11 calls. The second row is the best run: the calls double on each level, so the count is 2n - 1. The fourth row scans n items in each call, so each of the 11 levels does 1,024 units of work.
The same split gives very different costs. The tree tells you which one you have.
One call on a half makes a chain of about log n calls. Two calls on halves make a tree with 2n - 1 calls. Add a scan of n items in each call, and the cost becomes n log n.
So before you trust a recursion on a large input, draw its tree. Count the calls on each level and the work of one call.
Real production data brings edge cases.
A history of 1 day is a leaf: its best run is the day itself, 7 for [7]. The base case answers it, and the combine step never runs.
When every day takes money away, the best run is the least negative single day. For [-8, -3, -5, -2, -9] it is -2. The run must contain at least one day, so the base case returns the day, not 0.
Take seven days, [4, -1, 2, 6, -3, 5, 1]. They split into 3 and 4 days, and the best run is 14. The halves have different sizes, and the code handles it with the middle index. The depth is still about log2 n.
Any base to the power 0 is 1, also when the base is 0, so fast_power(5, 0, 13) returns 1. The base case answers it without a call.
This version writes fast_power(half) * fast_power(half). The answer is correct, but each level makes two calls where one was enough.
Counterexample: for an exponent of 1,024 it makes 4,095 calls instead of 12. For an exponent of 30 it makes 63 instead of 6.
Solve the half once, keep the answer in a variable, and use it twice.
Calling the half twice gives the same answer with 4,095 calls instead of 12 for an exponent of 1,024.
This version returns the best of the left half and the best of the right half.
Counterexample: for the days [5, -1, 5] the halves are [5] and [-1, 5], and the version returns 5. The best run is all three days, with a total of 9.
The combine step must join the best suffix of the left with the best prefix of the right.
This version returns 0 for a single day, as if an empty run were allowed.
Counterexample: for the days [-3, -1] it returns 0. The best run must have at least one day, so the answer is -1.
A base case must answer the smallest real problem, not an empty one.
Exercise · Break it: Find the exponent the base case never meets. This fast power answers the exponent 1 in the base case. Find an input where it does not give the right answer.
def fast_power(base, exp, mod):
if exp == 1:
return base % mod
half = fast_power(base, exp // 2, mod)
result = half * half % mod
if exp % 2 == 1:
result = result * base % mod
return resultSumming 1,000 numbers by halves works, but it gains nothing. The recursion makes 1,999 calls and 999 additions. A loop makes 999 additions and no calls.
Divide and conquer pays when the halves are independent and the combine step is cheap, and when splitting avoids work. Here every number must be read once anyway, so the calls only add overhead.
Your team lead brings four product changes. Each one uses the same three steps.
A feed sorts its posts by sorting two halves and merging them. The merge scans n items, so this is the fourth row of the table: about n log n (LeetCode 912: Sort an Array).
The budgeting problem of this lesson is the maximum subarray problem. The halves, the crossing run and the four numbers are the same (LeetCode 53: Maximum Subarray).
A poll wants the item chosen by more than half of the votes. Solve each half, and count each half's winner in the whole range (LeetCode 169: Majority Element).
A pricing page raises a rate to a long period. Halve the period, as in Template 1 (LeetCode 50: Pow(x, n)).
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how divide and conquer works, and why the combine step must look across the split. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have built it.
I split the problem into smaller problems of the same kind, and solve each with the same function. The base case answers the smallest problem at once.
Then I combine the answers. The combine step must cover what crosses the split, such as the best run across the middle.
I read the cost from the recursion tree. Two halves with constant work cost about 2n calls, and a scan of n in each call makes it n log n.
Divide and conquer has three steps. I split the problem into smaller problems of the same kind, I solve each one with the same function, and I combine the answers.
The base case answers the smallest problem at once. The combine step needs the most care, because an answer can cross the split. For the best run of days, I join the best suffix of the left half with the best prefix of the right half.
I read the cost from the recursion tree. One call on a half with constant work costs about log n. Two calls on halves cost about 2n. Two calls plus a scan of n cost n log n.
I solve a half once and reuse it. Calling it twice doubles the calls at every level. The depth is about log n, so the stack is small.
Checkpoint · Divide and conquer
Q1/10 What are the three steps of divide and conquer?
Answer: B
A call splits its problem into smaller problems of the same kind, solves each with the same function, and combines the answers. The base case answers the smallest problem at once.
Q2/10 The days are 5, -1 and 5, split into [5] and [-1, 5]. A version that returns the best of the two halves gives 5. What is the true best run?
Answer: B
The best run is all three days: 5 - 1 + 5 = 9. The version missed the run across the middle, which the combine step must cover.
Q3/10 What must the left half return so that the combine step can build the run across the middle?
Answer: B
The run across the middle joins the best suffix of the left to the best prefix of the right. The total lets a parent compute its own prefix and suffix.
Q4/10 The best-run recursion splits n days in halves with constant work in each call. How many calls does it make for 1,000 days?
Answer: C
A tree with n leaves has n - 1 inner nodes, so the calls are 2n - 1. For 1,000 days that is 1,999, and the real count was measured by running the template.
Q5/10 Fast power solves the half of the exponent once. About how many calls does an exponent of 1,024 make?
Answer: A
Each call halves the exponent, so there are 11 halvings and one call on 0: 12 calls in all. Calling the half twice makes 4,095.
Q6/10 A version of fast power writes power(half) * power(half). What changes?
Answer: B
The answer is correct, but each call now makes two calls. For an exponent of 1,024 that is 4,095 calls instead of 12.
Q7/10 Two calls on halves, after a scan of n items in each call, run on n = 1,024. About how much work is that?
Answer: C
Each of the 11 levels does 1,024 units of work, so the total is 11,264. That is n log n, as in a merge sort.
Q8/10 A base case returns 0 for a single day. For the days [-3, -1] it returns 0. Why is that wrong?
Answer: A
The best run must have at least one day, so the answer is -1. A base case must answer the smallest real problem, not an empty one.
Q9/10 How deep is the stack for the best-run recursion on 100,000 days?
Answer: B
The tree has 199,999 calls but only 18 levels, so the stack is 18 frames deep. Depth is the longest path, not the number of calls.
Q10/10 Which job gains nothing from divide and conquer?
Answer: C
A loop sums 1,000 numbers with 999 additions. The halves make 1,999 calls and the same additions, so the calls are overhead.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Power of a base | Pay | Easy | Halving an exponent and reusing the half |
| 2 | Closest pair on a line | Maps | Medium | Merging sorted halves and reading the pairs across the split |
| 3 | Every value a formula can take with brackets | Shop | Medium | Splitting at every operator and combining every pair |
| 4 | Longest stretch where every tag appears k times | Shop | Medium | Splitting at the items that cannot be in the answer |
| 5 | Quad tree of a floor plan | Freight | Medium | Four equal parts and a constant-time check |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.