Divide and conquer
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Divide and conquer solves a large problem in three steps: Split the problem into smaller independent subproblems (usually halves), Solve each subproblem recursively, and Combine their sub-answers into the final answer. Because halving reaches size 1 in ⌈ log₂ n ⌉ steps, divide-and-conquer keeps stack depth to O(log n) and powers algorithms from O(log n) fast exponentiation to O(n log n) Merge Sort.
Split, solve, combine
Divide and conquer splits a problem into smaller independent parts, solves each part recursively and combines the results, as merge sort does.
Divide and conquer splits a problem into smaller independent pieces, solves each piece recursively, and combines their answers. Every divide-and-conquer algorithm follows the same three-stage blueprint.
static int countEven(int[] a, int lo, int hi) { if (lo == hi) return a[lo] % 2 == 0 ? 1 : 0; // base case: one element int mid = lo + (hi - lo) / 2; // divide int left = countEven(a, lo, mid); // conquer the left half int right = countEven(a, mid + 1, hi); // conquer the right half return left + right; // combine}Unlike fib(n - 1) + fib(n - 2) where subproblems overlap heavily, divide-and-conquer splits an input into disjoint pieces (such as [lo .. mid] and [mid + 1 .. hi]) that never overlap.
- Divide (Split): Partition the input of size n into smaller independent pieces (typically of size n / 2).
- Conquer (Solve): Recursively solve each piece (stopping directly at the base case when n ≤ 1).
- Combine: Merge the solutions of the smaller pieces into the solution for the whole input.
Fast power
How do you compute xⁿ (for example, 3¹⁰⁰⁰⁰⁰⁰⁰⁰⁰, or Pow(x, n))? Multiplying x by itself n times (x * fastPow(x, n - 1)) takes O(n) multiplications and O(n) stack frames!
Example 1 · Brute force: multiply n times (O(n) time, O(1) space)
public class PowerByLoop { public static void main(String[] args) { double x = 1.0000001; int n = 1_000_000; double result = 1.0; int multiplications = 0; for (int i = 0; i < n; i++) { result *= x; multiplications++; } System.out.printf("x^n = %.4f%n", result); System.out.println("Multiplications: " + multiplications); }}x^n = 1.1052 Multiplications: 1000000
What this code does
- Raising 1.0000001 to the power 1,000,000 takes 1,000,000 multiplications.
- It is slow because every power is built one factor at a time, ignoring that x^n = (x^(n/2))².
Example 2 · Optimal: fast power halves the exponent (O(log n) time, O(log n) stack)
public class FastPowerDemo { public static double myPow(double x, int n) { long exp = n; // widen to long so n = Integer.MIN_VALUE (-2^31) does not overflow when negated! if (exp < 0) { x = 1.0 / x; exp = -exp; } return fastPow(x, exp); }
private static double fastPow(double x, long n) { if (n == 0) return 1.0; double half = fastPow(x, n / 2); if (n % 2 == 0) { return half * half; } else { return half * half * x; } }
public static void main(String[] args) { System.out.println("2^10 = " + myPow(2.0, 10)); System.out.println("2^-3 = " + myPow(2.0, -3)); }}2^10 = 1024.0 2^-3 = 0.125
What this code does
- Widening int n to long exp prevents -Integer.MIN_VALUE from overflowing back to Integer.MIN_VALUE.
- Computing half = fastPow(x, n / 2) once makes only 1 recursive call per level: O(log n) time.
- The same idea applied to 1.0000001 and exponent 1,000,000 needs only 27 multiplications instead of 1,000,000, because every call halves n.
Notice that xⁿ can be computed from x^(⌊ n / 2 ⌋) in one recursive call:
- Compute
half = fastPow(x, n / 2)once and save it in a variable. - If
nis even (n = 2k): x²ᵏ = (xᵏ)² = half × half. - If
nis odd (n = 2k + 1): x²ᵏ⁺¹ = (xᵏ)² · x = half × half × x. Becausenis halved on every call, n = 1,000,000,000 takes at most 30 recursive calls: O(log n) time and O(log n) stack space!
long half = fastPow(x, n / 2); in a variable and compute half * half. If you write fastPow(x, n / 2) * fastPow(x, n / 2), you make TWO recursive calls at every level and turn O(log n) back into O(n)!Maximum by halves
Compare finding the maximum of arr[0 .. n - 1] linearly (Math.max(arr[i], maxFrom(arr, i + 1))) vs by halves (Math.max(maxRange(arr, lo, mid), maxRange(arr, mid + 1, hi))).
Example 3 · Maximum and sum by halves with O(log n) stack depth
public class MaxByHalvesDemo { static int maxDepth = 0;
public static int maxInRange(int[] arr, int lo, int hi, int depth) { maxDepth = Math.max(maxDepth, depth); if (lo == hi) { return arr[lo]; // base case: 1-element subarray } int mid = lo + (hi - lo) / 2; int leftMax = maxInRange(arr, lo, mid, depth + 1); int rightMax = maxInRange(arr, mid + 1, hi, depth + 1); return Math.max(leftMax, rightMax); }
public static void main(String[] args) { int[] arr = {12, 45, 7, 91, 23, 64, 88, 19}; int maxVal = maxInRange(arr, 0, arr.length - 1, 1); System.out.println("Max: " + maxVal + ", peak stack depth: " + maxDepth); }}Max: 91, peak stack depth: 4
What this code does
- For 8 elements, the range splits 8 -> 4 -> 2 -> 1, reaching a maximum stack depth of 4 (log2(8) + 1).
- Even on 1,000,000 elements, peak stack depth is only 21 frames.
In detail:
- Both inspect every element and perform n - 1 comparisons (O(n) time).
- However, linear recursion has a recursion tree of height n (O(n) stack frames, crashing with
StackOverflowErroraround n = 15,000), whereas maximum by halves has a balanced binary recursion tree of height ⌈ log₂ n ⌉ (O(log n) stack space—only 20 frames for n = 1,000,000!).
Order of execution
Maximum by halves
Tap the steps in the order one call of maxRange runs them.
A preview of merge sort
What if instead of just taking Math.max of the left and right halves, we sort the left half arr[lo .. mid], sort the right half arr[mid + 1 .. hi], and then merge the two sorted halves using two pointers in O(n) time?
Example 4 · Preview of Merge Sort: splitting in halves and merging sorted subarrays
import java.util.Arrays;
public class MergeSortPreviewDemo { public static void mergeSort(int[] a, int lo, int hi) { if (lo >= hi) return; // base case: 0 or 1 element is already sorted int mid = lo + (hi - lo) / 2; mergeSort(a, lo, mid); // Solve left half mergeSort(a, mid + 1, hi); // Solve right half merge(a, lo, mid, hi); // Combine sorted halves }
private static void merge(int[] a, int lo, int mid, int hi) { int[] temp = new int[hi - lo + 1]; int i = lo, j = mid + 1, k = 0; while (i <= mid && j <= hi) { if (a[i] <= a[j]) temp[k++] = a[i++]; else temp[k++] = a[j++]; } while (i <= mid) temp[k++] = a[i++]; while (j <= hi) temp[k++] = a[j++]; System.arraycopy(temp, 0, a, lo, temp.length); }
public static void main(String[] args) { int[] nums = {38, 27, 43, 3, 9, 82, 10}; mergeSort(nums, 0, nums.length - 1); System.out.println(Arrays.toString(nums)); }}[3, 9, 10, 27, 38, 43, 82]
What this code does
- Split: mid divides [lo..hi] into two halves.
- Solve: two recursive calls sort the two halves.
- Combine: two-pointer merge combines the two sorted halves in O(hi - lo + 1) linear time.
That is Merge Sort! Its recursion tree has log₂ n + 1 levels, and merging all subarrays across any single level takes O(n) total work, giving O(n log n) time even in the worst case.
Next step
Check your understanding
10 quick questions