Divide and Conquer

Split a problem into smaller copies of itself, solve each copy, and combine the answers. The recurrence that describes the split tells you the running time.

Overview

The idea

A divide and conquer algorithm solves a big problem by solving smaller copies of the same problem. It always has three steps.

  • Divide: split the input into pieces, usually halves.
  • Conquer: solve each piece with the same algorithm, down to a base case small enough to answer directly.
  • Combine: build the answer for the whole input from the answers for the pieces.

The pieces are solved by the same function; the combine step is where each algorithm differs. Six well-known algorithms show the range.

  • Binary search: divide by looking at one half. There is nothing to combine, and the cost is O(log n).
  • Merge sort: divide into two halves, and combine by merging two sorted lists in O(n). The cost is O(n log n).
  • Quicksort: divide by partitioning around a pivot. There is nothing to combine, because the pieces are already in place. The cost is O(n log n) expected.
  • Sorted array to balanced BST: divide by making the middle value the root, and combine by attaching the two subtrees in O(1). The cost is O(n).
  • Fast power x^n: divide by computing x^(n/2) once and squaring it, which is one multiplication to combine. The cost is O(log n) multiplications.
  • Count inversions: divide into two halves, and combine by counting cross pairs while merging, in O(n). The cost is O(n log n).

The pieces must be independent: solving one must not need the answer of another. When the pieces overlap, as in Fibonacci or most path-counting problems, the same recursion repeats work and dynamic programming is the right tool.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio