Skip to main content

Analyzing Divide and Conquer Algorithms

13 min readRead first: The Divide and Conquer Scheme

The loops of iterative algorithms can be analyzed by counting iterations, as we did in the first chapter. Recursive algorithms need a different tool: the execution time is expressed in terms of itself applied to smaller sizes, giving a recurrence equation. Fortunately, most divide and conquer algorithms follow one of two very regular patterns, and for both of them the solution is known in general. This lesson presents those two patterns, explains where their formulas come from, and shows how to apply them.

What you will learn in this lesson
  • How to model a divide and conquer algorithm with the parameters aa, bb and kk.
  • The complexity formulas for division and subtraction schemes, and the intuition behind them (the recursion tree).
  • How to identify aa, bb and kk in real code, and the most common mistakes.
  • The limits of these formulas.

The Parameters aa, bb and kk​

Both schemes are described by three parameters:

  • aa: the number of subproblems (recursive calls) executed in each invocation;
  • bb: how the size decreases: each subproblem has size n/bn / b (division) or n−bn - b (subtraction), where bb is a constant;
  • kk: the cost of the work done in each invocation excluding the recursive calls (dividing and combining) is O(nk)O(n^k), a polynomial.

The base case takes constant time (or, more generally, c⋅nkc \cdot n^k for its small size).


Before the Formulas: a Recurrence with Numbers​

A recurrence such as T(n)=2 T(n/2)+nT(n) = 2\,T(n/2) + n often looks like magic, but it is just the code described in one line. Take Mergesort: sorting nn elements means sorting two halves and then merging them, which goes through the nn elements once. If T(n)T(n) is the time to sort nn elements:

T(n)=2 T(n/2)⏟two halves+n⏟merge,T(1)=1T(n) = \underbrace{2\,T(n/2)}_{\text{two halves}} + \underbrace{n}_{\text{merge}}, \qquad T(1) = 1

Nothing stops us from computing it by hand, from small to large, exactly as the computer would:

nnT(n)=2 T(n/2)+nT(n) = 2\,T(n/2) + nValue
1base case1
22⋅T(1)+2=2⋅1+22 \cdot T(1) + 2 = 2 \cdot 1 + 24
42⋅T(2)+4=2⋅4+42 \cdot T(2) + 4 = 2 \cdot 4 + 412
82⋅T(4)+8=2⋅12+82 \cdot T(4) + 8 = 2 \cdot 12 + 832
162⋅T(8)+16=2⋅32+162 \cdot T(8) + 16 = 2 \cdot 32 + 1680

Now look for the pattern, as with the loops of the first chapter. Each value is exactly nlog⁡2n+nn \log_2 n + n: for n=16n = 16, 16⋅4+16=8016 \cdot 4 + 16 = 80. The reason is the recursion tree: every level of the tree does nn units of merging in total (one merge of 16, two of 8, four of 4...), and there are log⁡2n\log_2 n levels. Keeping the important part, Mergesort is O(nlog⁡n)O(n \log n).

The formulas below do exactly this, once and for all, for every recurrence of the same shape. When one of them looks mysterious, go back to these three steps: write the recurrence from the code, compute a few values by hand, and look at the work per level of the tree.


Division Scheme​

The execution time satisfies:

T(n)={a⋅T(n/b)+c⋅nkif n is greater than the base casec⋅nkin the base caseT(n) = \begin{cases} a \cdot T(n/b) + c \cdot n^k & \text{if } n \text{ is greater than the base case} \\ c \cdot n^k & \text{in the base case} \end{cases}

and its solution is:

T(n)∈{O(nk)if a<bkO(nklog⁡n)if a=bkO(nlog⁡ba)if a>bkT(n) \in \begin{cases} O(n^k) & \text{if } a \lt b^k \\ O(n^k \log n) & \text{if } a = b^k \\ O(n^{\log_b a}) & \text{if } a \gt b^k \end{cases}

This result is a particular case of the so-called master theorem.

Where does it come from? The recursion tree​

Draw the tree of recursive calls. The root is the original problem, of size nn. It has aa children of size n/bn/b, each of which has aa children of size n/b2n/b^2, and so on, until the base case. The tree has about log⁡bn\log_b n levels.

Recursion tree of the division scheme with a = 2: level i has a to the i subproblems of size n over b to the inn/bn/bn/b²n/b²n/b²n/b²⋮leaves: base casessubproblemswork at the level1c·nᵏac·nᵏ · (a/bᵏ)a²c·nᵏ · (a/bᵏ)²a^(log_b n) = n^(log_b a)∝ n^(log_b a)total: a geometric series of ratio a/bᵏ
The recursion tree of the division scheme. Level i has aⁱ subproblems of size n/bⁱ; multiplying the number of subproblems by the work of each one gives the work of the level.
LevelNumber of subproblemsSize of each oneNon-recursive work at the level
011nnc⋅nkc \cdot n^k
1aan/bn/ba⋅c⋅(n/b)k=c⋅nk⋅abka \cdot c \cdot (n/b)^k = c \cdot n^k \cdot \frac{a}{b^k}
2a2a^2n/b2n/b^2c⋅nk⋅(abk)2c \cdot n^k \cdot \left(\frac{a}{b^k}\right)^2
iiaia^in/bin/b^ic⋅nk⋅(abk)ic \cdot n^k \cdot \left(\frac{a}{b^k}\right)^i
log⁡bn\log_b n (leaves)alog⁡bn=nlog⁡baa^{\log_b n} = n^{\log_b a}constantproportional to nlog⁡ban^{\log_b a}

The total time is the sum of all levels: c⋅nkc \cdot n^k multiplied by a geometric series of ratio r=abkr = \frac{a}{b^k}. Everything depends on that ratio:

  • a<bka \lt b^k (r<1r \lt 1): the work decreases from each level to the next. The sum is dominated by the first term: the work at the root, O(nk)O(n^k). The subproblems shrink faster than they multiply.
  • a=bka = b^k (r=1r = 1): every level does the same work, c⋅nkc \cdot n^k, and there are log⁡bn\log_b n levels: O(nklog⁡n)O(n^k \log n).
  • a>bka \gt b^k (r>1r \gt 1): the work increases from each level to the next. The sum is dominated by the last level, the leaves, whose number is alog⁡bna^{\log_b n}. By the logarithm rule xlog⁡by=ylog⁡bxx^{\log_b y} = y^{\log_b x} from the asymptotic notation lesson, alog⁡bn=nlog⁡baa^{\log_b n} = n^{\log_b a}: O(nlog⁡ba)O(n^{\log_b a}).
Where the work concentrates: at the root, evenly, or at the leavesa < bᵏ: O(nᵏ)work shrinks level by levela = bᵏ: O(nᵏ log n)same work at every levela > bᵏ: O(n^(log_b a))work grows towards the leavesrootleaves
The work of each level of the tree in the three cases. The ratio a/bᵏ decides whether the root, all the levels equally, or the leaves dominate the total.

So the three cases correspond to three situations: the cost is concentrated at the top of the tree, evenly spread over all levels, or concentrated at the bottom.

ProofThe division formula

Subtraction Scheme​

The execution time satisfies:

T(n)={a⋅T(n−b)+c⋅nkif n is greater than the base casec⋅nkin the base caseT(n) = \begin{cases} a \cdot T(n - b) + c \cdot n^k & \text{if } n \text{ is greater than the base case} \\ c \cdot n^k & \text{in the base case} \end{cases}

and its solution is:

T(n)∈{O(nk+1)if a=1O(an/b)if a>1T(n) \in \begin{cases} O(n^{k+1}) & \text{if } a = 1 \\ O(a^{n / b}) & \text{if } a \gt 1 \end{cases}

(Some textbooks also list a case a<1a \lt 1, but it cannot happen in practice: a recursive algorithm makes at least one call in its general case.)

The intuition is again in the recursion tree, which now has about n/bn / b levels:

  • a=1a = 1: a single chain of n/bn/b calls, with sizes n,n−b,n−2b,…n, n - b, n - 2b, \dots. The work at each one is at most c⋅nkc \cdot n^k, and there are n/bn/b of them: O(nk+1)O(n^{k+1}). A loop of nn iterations whose body costs O(nk)O(n^k), written recursively.
  • a>1a \gt 1: the number of calls multiplies by aa at each level, through n/bn/b levels: an/ba^{n/b} calls. The algorithm is exponential, and the non-recursive work does not even matter.
Subtraction scheme: with a = 1 the calls form a chain; with a = 2 they double at every levela = 1: a chain of n/b callsnn − bn − 2b⋮basea = 2: the number of calls doubles at each level1248after n/b levels: 2^(n/b) calls, exponential
The recursion trees of the subtraction scheme. With one recursive call the calls form a chain of n/b links; with two, the number of calls doubles at every level.
Avoid subtraction with several subproblems

An algorithm with a>1a \gt 1 in a subtraction scheme is exponential, and therefore unusable except for very small inputs. If you find yourself writing two or more recursive calls on n−1n - 1 (or n−2n - 2...), stop and think: most likely the same subproblems are being solved many times, and a different technique (an iterative version, or dynamic programming) is needed.

ProofThe subtraction formula

Identifying aa, bb and kk​

To apply the formulas, look at the code of the recursive method and answer three questions:

  1. How many recursive calls are executed in one invocation (in the general case)? That is aa. Count the calls that are actually executed, not the ones that are written: in binary search there are two calls in the code, but only one of them runs in each invocation, so a=1a = 1. And a call inside a loop that runs mm times counts mm times.
  2. What is the size of each recursive call? If it is n/bn/b, the scheme is division; if it is n−bn - b, subtraction.
  3. What is the cost of everything else (loops, copies, partitions, merges)? If it is O(nk)O(n^k), that gives kk. A constant amount of work means k=0k = 0.

For example, in Mergesort:

public void mergesort(int[] v, int left, int right) {
if (left < right) { // base case: one element, constant time
int center = (left + right) / 2; // O(1)
mergesort(v, left, center); // call 1, on half the elements
mergesort(v, center + 1, right); // call 2, on the other half
merge(v, left, center, right); // O(n): goes through the n elements once
}
}

Two calls are executed (a=2a = 2), each one on half of the elements (b=2b = 2, division), and the rest of the work is dominated by the linear merge (k=1k = 1). Since a=2=bk=21a = 2 = b^k = 2^1, Mergesort is O(nlog⁡n)O(n \log n).

Examples​

AlgorithmaabbkkCaseComplexity
Binary search120a=bka = b^k (1=11 = 1)O(log⁡n)O(\log n)
Sum of a vector by division220a>bka \gt b^k (2>12 \gt 1)O(nlog⁡22)=O(n)O(n^{\log_2 2}) = O(n)
Mergesort221a=bka = b^k (2=22 = 2)O(nlog⁡n)O(n \log n)
Quicksort (balanced partitions)221a=bka = b^kO(nlog⁡n)O(n \log n)
Tennis tournament222a<bka \lt b^k (2<42 \lt 4)O(n2)O(n^2)
Multiplication of large integers (4 products)421a>bka \gt b^k (4>24 \gt 2)O(nlog⁡24)=O(n2)O(n^{\log_2 4}) = O(n^2)
Karatsuba multiplication (3 products)321a>bka \gt b^k (3>23 \gt 2)O(nlog⁡23)≈O(n1.585)O(n^{\log_2 3}) \approx O(n^{1.585})

The naive Fibonacci does not fit the scheme exactly, because its two calls have different sizes, n−1n - 1 and n−2n - 2. Replacing n−2n - 2 by n−1n - 1 can only make the tree larger, so the scheme with a=2a = 2, b=1b = 1 gives an upper bound, O(2n)O(2^n). The exact growth is about 1.618n1.618^n, still exponential.

Notice how Quicksort appears in both tables: with perfectly balanced partitions, it follows a division scheme (a=2a = 2, b=2b = 2, k=1k = 1); with the most unbalanced ones, a subtraction scheme in which one of the two parts is empty, so only one non-trivial call remains (a=1a = 1, b=1b = 1, k=1k = 1). Both formulas confirm what we found in the sorting chapter: O(nlog⁡n)O(n \log n) in the best case and O(n2)O(n^2) in the worst.

🧠 Checkpoint: Analyze these schemes

Question: Give the complexity of (1) an algorithm that splits a problem of size nn into 8 subproblems of size n/2n/2 and combines them in O(n2)O(n^2), and (2) the same with 7 subproblems.

Answer: (1) a=8a = 8, b=2b = 2, k=2k = 2: a=8>bk=4a = 8 \gt b^k = 4, so O(nlog⁡28)=O(n3)O(n^{\log_2 8}) = O(n^3). This is the divide and conquer multiplication of n×nn \times n matrices with 8 products of half-size blocks: no better than the classic algorithm. (2) With a=7a = 7: O(nlog⁡27)≈O(n2.81)O(n^{\log_2 7}) \approx O(n^{2.81}). This is Strassen's algorithm (Strassen, 1969), which saves one block multiplication at the cost of more additions, and beats the classic cubic algorithm for large matrices. The same trick, saving one recursive call, makes Karatsuba's multiplication faster.


How Each Parameter Affects the Cost​

The formulas give useful design guidance:

  • Reducing aa (fewer subproblems) is often the key to a faster algorithm when a>bka \gt b^k: Karatsuba (4 to 3 products) and Strassen (8 to 7) are famous examples.
  • Reducing kk (cheaper division and combination) helps when a≤bka \le b^k. For example, Mergesort with an O(n2)O(n^2) merge would be O(n2)O(n^2) instead of O(nlog⁡n)O(n \log n).
  • Division beats subtraction: dividing the size by 2 instead of subtracting 1 turns O(n)O(n) levels into O(log⁡n)O(\log n), and can turn an exponential algorithm into a polynomial one.

Limits of the Formulas​

These formulas cover the most common cases, but not all of them:

  • Subproblems of different sizes. If an algorithm divides into parts of sizes n/3n/3 and 2n/32n/3, or into parts whose size depends on the data (Quicksort with random pivots, Quickselect), the formulas do not apply directly. The recursion tree, or probabilistic analysis, is needed. For example, Quicksort's average case is O(nlog⁡n)O(n \log n), and Quickselect's average case is O(n)O(n), although neither follows exactly any of the two schemes.
  • Non-polynomial non-recursive work. If dividing and combining costs, for example, O(nlog⁡n)O(n \log n), kk is not an integer power. The recurrence T(n)=2T(n/2)+nlog⁡nT(n) = 2T(n/2) + n \log n has solution O(nlog⁡2n)O(n \log^2 n), which the simple formulas do not give. The general master theorem covers many of these cases.
  • Exact constants. The formulas give the order of growth, not the exact time.

When an algorithm does not fit the schemes, the safest method is to draw the recursion tree, compute the work at each level and add it up, as we did above.


Predicting Execution Times​

Once the complexity is known, the techniques of the first chapter apply directly. For example, if Mergesort (O(nlog⁡n)O(n \log n)) takes 2 seconds for n=220n = 2^{20}, for n=222n = 2^{22} it will take about

t2=222⋅22220⋅20⋅2≈8.8 secondst_2 = \frac{2^{22} \cdot 22}{2^{20} \cdot 20} \cdot 2 \approx 8.8 \text{ seconds}

And if the Towers of Hanoi (O(2n)O(2^n)) take 1 second for 20 discs, then 30 discs will take about 210=1,0242^{10} = 1{,}024 seconds (17 minutes), and 64 discs, about 2442^{44} seconds: more than 500,000 years.

Common mistakes
  • Counting the recursive calls written instead of those executed. Binary search writes two calls but executes one: a=1a = 1.
  • Taking kk from the recursive calls. kk is the cost of the non-recursive work (dividing and combining), O(nk)O(n^k).
  • Applying the division formulas to a subtraction scheme. First decide whether the size is divided (n/bn/b) or reduced (n−bn - b).

Summary​

  • Divide and conquer algorithms are analyzed with recurrences, characterised by aa (number of subproblems), bb (how the size decreases) and kk (cost of dividing and combining, O(nk)O(n^k)).
  • Division (n/bn/b): O(nk)O(n^k) if a<bka \lt b^k; O(nklog⁡n)O(n^k \log n) if a=bka = b^k; O(nlog⁡ba)O(n^{\log_b a}) if a>bka \gt b^k.
  • Subtraction (n−bn - b): O(nk+1)O(n^{k+1}) if a=1a = 1; O(an/b)O(a^{n/b}), exponential, if a>1a \gt 1.
  • The recursion tree explains the formulas: the cost is concentrated at the top, evenly spread, or concentrated at the leaves.
  • Count the recursive calls that are executed, not the ones written. Subproblems of unequal or data-dependent size need a specific analysis.

Practice​

  • 🌳 Draw the tree. Draw the recursion tree of T(n)=3T(n/2)+nT(n) = 3T(n/2) + n for n=16n = 16, write the work at each level, and check that the total grows like nlog⁡23n^{\log_2 3}.
  • 🔍 Identify the parameters. Write a recursive method that searches for the maximum of a vector by dividing it into three parts. What are aa, bb and kk? What is its complexity?
  • ⚖️ Compare designs. Problem A is solved by dividing into 2 halves and combining in O(n2)O(n^2); problem B by dividing into 4 quarters and combining in O(n)O(n). Which algorithm has the better complexity?
  • 💻 Measure. In lab session 3 you will measure recursive models of each type. Before measuring, predict how the time should grow when nn doubles (division) or when nn increases by a constant (subtraction with a>1a \gt 1), and then compare with your measurements.
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.