Skip to main content

Summary: Divide and Conquer

Everything on one page, to review the chapter before moving on.

Key ideas​

  • Divide and conquer divides a problem into smaller subproblems of the same kind, solves them recursively and combines their solutions (The Divide and Conquer Scheme).
  • The number of subproblems should be small, and the subproblems independent. When they repeat, dynamic programming is the right tool.
  • With a single subproblem (a=1a = 1) the process is a reduction, often better written as a loop. Recursion uses stack memory proportional to its depth.
  • Count the recursive calls that are executed, not the ones written (Analyzing Divide and Conquer).
  • Discarding the subproblems that cannot contain the answer is what makes binary search and Quickselect fast (Majority, Mode and Median).

Solving the recurrences​

With aa subproblems and a cost of dividing and combining in O(nk)O(n^k) (Analyzing Divide and Conquer):

SchemeConditionComplexity
Division (n/bn/b)a<bka \lt b^kO(nk)O(n^k)
Division (n/bn/b)a=bka = b^kO(nklog⁡n)O(n^k \log n)
Division (n/bn/b)a>bka \gt b^kO(nlog⁡ba)O(n^{\log_b a})
Subtraction (n−bn - b)a=1a = 1O(nk+1)O(n^{k+1})
Subtraction (n−bn - b)a>1a \gt 1O(an/b)O(a^{n/b}), exponential

At a glance​

ProblemAlgorithmComplexityLesson
FactorialSubtraction, a=1a = 1O(n)O(n)Numbers and Searches
Search in a sorted vectorBinary searchO(log⁡n)O(\log n)Numbers and Searches
FibonacciNaive recursionΘ(φn)\Theta(\varphi^n), exponentialNumbers and Searches
FibonacciIterative / matrix powerO(n)O(n) / O(log⁡n)O(\log n)Numbers and Searches
Greatest common divisorEuclid's algorithmLinear in the number of digitsNumbers and Searches
SortingMergesortO(nlog⁡n)O(n \log n)Classic Problems
SortingQuicksortO(nlog⁡n)O(n \log n) best, O(n2)O(n^2) worstClassic Problems
Towers of HanoiSubtraction, a=2a = 2O(2n)O(2^n)Classic Problems
Large integersKaratsubaO(n1.585)O(n^{1.585})Classic Problems
Tennis tournamentDivision, k=2k = 2O(n2)O(n^2)Classic Problems
Tromino puzzle (nn = side)Division, a=4a = 4O(n2)O(n^2)Classic Problems
Majority element, modeSorting firstO(nlog⁡n)O(n \log n)Majority, Mode and Median
MedianQuickselectO(n)O(n) average, O(n2)O(n^2) worstMajority, Mode and Median

When to use it​

  • The problem splits into independent subproblems of the same kind, and their solutions combine cheaply.
  • Avoid it when the subproblems overlap (naive Fibonacci): use dynamic programming instead.
  • Prefer division schemes (n/bn/b) to subtraction schemes (n−bn - b) with several subproblems, which are exponential.
Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.