Command Palette

Search for a command to run...

← All patterns

Pattern · Recursion

Divide and Conquer

Split the input into halves, solve each half recursively, and combine the results.

Time O(n log n) typically · Space O(n) for merging, O(log n) stack

Taught in Module 14: Sorting and Divide & Conquer

Think of it like this

Sorting a big pile of exam papers: split it between two helpers, let each sort their half, then merge the two sorted piles.

Clues that point here

  • → Sorting
  • → Counting inversions
  • → The answer for a range can be built from its halves
  • → O(n log n) expected

Not this pattern when

  • ✕ The halves overlap heavily (DP)
  • ✕ A single pass suffices

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Divide and Conquer · template
void mergeSort(int[] a, int lo, int hi) {
    if (lo >= hi) return;
    int mid = (lo + hi) >>> 1;
    mergeSort(a, lo, mid);
    mergeSort(a, mid + 1, hi);
    merge(a, lo, mid, hi);        // combine two sorted halves
}

Common versions

  • Merge sort
  • Quick sort and quickselect
  • Count inversions
  • Maximum subarray (D&C version)

Practice problems with this pattern

Related patterns