Learn › Recursion

Divide & conquer

Split a problem, solve smaller copies, and combine the answers with recurrence maths. · 9 min read

Divide and conquer is recursion with a particular shape: split the input into smaller independent pieces, solve each piece recursively, then combine their answers. The pattern is powerful because the recursion tree often has only log n levels.

The template

def divide_conquer(problem):
    if small(problem):
        return solve_directly(problem)
    left, right = split(problem)
    a = divide_conquer(left)
    b = divide_conquer(right)
    return combine(a, b)

Interactive visualization: The recursion tree for T(n)=2T(n/2)+n — step through it frame by frame on this page.

Merge sort recurrence

Why merge sort is n log n
  1. T(n) = 2T(n/2) + cn — Two half-sized recursive sorts, then a linear merge.
  2. level 0 work = cn — One problem of size n.
  3. level 1 work = 2 × c(n/2) = cn — Two half-sized problems still total n work.
  4. every level costs cn — The subproblem sizes across a level add to n.
  5. number of levels = log₂ n — Halve until size 1.
  6. cn log₂ n + O(n leaves) — Leaves add linear work, dominated by n log n.

Result: T(n) = O(n log n)

The quick Master Theorem intuition

For recurrences of the form T(n)=aT(n/b)+f(n), compare the combine work f(n) to n^{log_b a}:

  • If f(n) is smaller, the leaves dominate.
  • If f(n) is the same size, every level contributes equally → multiply by log n.
  • If f(n) is larger, the root/combine work dominates.

For merge sort, a=2, b=2, so n^{log₂2}=n; combine work is also n, so the answer is O(n log n).

Previous: Recursion & the call stack · Next: Backtracking

More in Recursion