PDSA Interactive Book
Week 8

Divide and Conquer

Split the problem, solve the pieces, stitch the answers together — and how to count the cost.

After this chapter you can…
  • write and solve recurrences for recursive algorithms (recursion tree, master theorem)
  • implement fast exponentiation and count inversions
  • explain quickselect and median of medians
  • see why fewer recursive calls beats doing less work per call

Divide and conquer

Many problems yield to the same three-step recipe:

Put in order

The divide-and-conquer recipe

You have already met it: merge sort (divide = split in half, combine = merge) and quicksort (divide = partition, combine = nothing) and binary search (discard half). This week we learn how to analyse such algorithms and meet new applications.

Recurrences: the cost of a recursive algorithm

If an algorithm splits a size-n problem into a subproblems of size n/b and spends f(n) on dividing and combining, its running time satisfies the recurrence

T(n) = a · T(n/b) + f(n)

AlgorithmRecurrenceSolution
Binary searchT(n) = T(n/2) + 1Θ(log n)
Merge sortT(n) = 2T(n/2) + nΘ(n log n)
Quicksort, balanced splitsT(n) = 2T(n/2) + nΘ(n log n)
Quicksort, worst caseT(n) = T(n−1) + nΘ(n²)
Naive FibonacciT(n) = T(n−1) + T(n−2) + 1Θ(φⁿ) ≈ 1.618ⁿ
Karatsuba multiplicationT(n) = 3T(n/2) + nΘ(n^1.585)

Unrolling a recursion tree

Draw the calls as a tree. For T(n) = 2T(n/2) + n: level 0 does n work, level 1 has two calls each doing n/2 — again n in total — and so on. There are log₂ n levels, each costing n, so the total is n log₂ n.

Recursion tree — set a, b and the combine cost, and see the work per levelInteractive
Master theorem (the useful cases)

For T(n) = a·T(n/b) + n^d, compare a with b^d:

  • a < b^d → the top level dominates: Θ(n^d)
  • a = b^d → every level costs the same: Θ(n^d log n)
  • a > b^d → the leaves dominate: Θ(n^(log_b a))
Python · editable
Expected output: merge sort Theta(n log n) binary search Theta(log n) karatsuba Theta(n^1.585) naive matrix Theta(n^3.000)
Check yourself

Which case of the master theorem applies to T(n) = 2T(n/2) + n?

Check yourself

Using the master theorem, solve T(n) = 4T(n/2) + n. What exponent k is in Θ(n^k)?

Predict the output

What does this print? (type the exact output)

def T(n):
    return 1 if n <= 1 else 2 * T(n // 2) + n
print(T(8))

Fast exponentiation

Computing xⁿ by multiplying n − 1 times is O(n). Divide and conquer: xⁿ = (x^(n/2))² for even n, and x · x^(n−1) for odd n. Each step halves the exponent: O(log n) multiplications.

Python · editable
Expected output: True after 7 recursive steps 4611686018427387904
Call once, not twice

Writing power(x, n//2) * power(x, n//2) makes two calls per level: T(n) = 2T(n/2) + 1 = Θ(n) — all the benefit lost. Store the result in a variable.

Check yourself

About how many multiplications does fast exponentiation need to compute x¹⁰⁰⁰⁰⁰⁰?

Counting inversions

How different are two rankings? Say you and a friend rank 5 films. An inversion is a pair of items in the wrong relative order: positions i < j with A[i] > A[j]. The number of inversions measures how far from sorted a list is (0 = sorted, n(n−1)/2 = reversed). Counting all pairs is O(n²). Merge sort counts them in O(n log n).

When merging two sorted halves L and R: if we take an element from R while k elements remain in L, it jumps ahead of exactly those k larger elements — that is k cross inversions. Add them up during the merge.

Python · editable
Expected output: ([1, 2, 3, 4, 5], 3) ([1, 2, 3, 4, 5], 10)
Inversions — see which pairs are out of orderInteractive
Predict the output

How many inversions does [3, 1, 2] have?

A = [3, 1, 2]
print(sum(1 for i in range(len(A)) for j in range(i + 1, len(A)) if A[i] > A[j]))
Check yourself

The maximum number of inversions in a list of n distinct items is…

Selection: the k-th smallest element

Sorting finds the median in O(n log n). Can we do better? Quickselect partitions around a pivot like quicksort but recurses into only the side that contains the k-th item.

Python · editable
Expected output: 5 5

With a good pivot (always near the middle) the sizes go n, n/2, n/4, … so total work is n + n/2 + … = 2n = O(n). With a bad pivot it is O(n²). A random pivot gives expected O(n).

Median of medians — a guaranteed good pivot

Split the list into groups of 5, find each group's median (constant time per group), then recursively find the median of those medians and use it as pivot. This pivot is guaranteed to have at least ~30% of the elements on each side, so the recurrence is T(n) ≤ T(n/5) + T(7n/10) + O(n), which solves to Θ(n) worst case.

Median of medians — pick the pivot step by stepInteractive
Check yourself

Quickselect with a random pivot runs in expected time…

Check yourself

Why is the median-of-medians pivot special?

Predict the output

What does this print?

def kth(L, k):
    p = L[0]
    lo = [x for x in L if x < p]
    eq = [x for x in L if x == p]
    hi = [x for x in L if x > p]
    if k <= len(lo): return kth(lo, k)
    if k <= len(lo) + len(eq): return p
    return kth(hi, k - len(lo) - len(eq))
print(kth([9, 3, 7, 1, 5], 2), kth([9, 3, 7, 1, 5], 5))

Multiplying big numbers

The schoolbook method multiplies two n-digit numbers in n² digit operations. Split x = a·10^h + b and y = c·10^h + d. Then xy = ac·10^(2h) + (ad + bc)·10^h + bd needs four half-size products. Karatsuba noticed ad + bc = (a + b)(c + d) − ac − bd, so three products suffice: T(n) = 3T(n/2) + n = Θ(n^1.585).

Python · editable
Expected output: True True
Check yourself

Karatsuba improves on the schoolbook method by…

Chapter challenge — Week 8

…
Check yourself

Merge sort's recurrence is…

Predict the output

What does this print? (type the exact output)

def inv(A):
    return sum(1 for i in range(len(A)) for j in range(i + 1, len(A)) if A[i] > A[j])
print(inv([4, 3, 2, 1]))
Check yourself

Solve T(n) = 8T(n/2) + n² with the master theorem.

Put in order

Counting inversions with merge sort.

Check yourself

How many multiplications of big numbers does one Karatsuba step use?

Check yourself

Why does power(x, n//2) * power(x, n//2) destroy the speed-up?

Check yourself

Which are divide-and-conquer algorithms?

Check yourself

Quickselect's expected time is O(n), but sorting needs…

Practice on LeetCode

Divide and conquer, recurrences, selection and counting inversions.

How to practise

Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.

0 / 10 solvedTick a problem when you have solved it — saved in this browser.
ProblemLevelPractises
Pow(x, n) ↗Mediumfast exponentiation: O(log n)
Majority Element ↗Easydivide and conquer (also Boyer–Moore voting)
Maximum Subarray ↗Mediumtry the divide-and-conquer solution, then Kadane
Sort an Array ↗Mediummerge sort
Kth Largest Element in an Array ↗Mediumquickselect
Different Ways to Add Parentheses ↗Mediumsplit at each operator, combine the results
Multiply Strings ↗Mediumbig-number multiplication
Count of Smaller Numbers After Self ↗Hardmerge-sort counting, like inversions
Reverse Pairs ↗Hardinversion counting during merge
Median of Two Sorted Arrays ↗Hardbinary search / divide and conquer

Key takeaways

  • Divide, conquer recursively, combine. The running time is captured by a recurrence like T(n) = a·T(n/b) + f(n).
  • Master theorem for a·T(n/b) + n^d: compare a with b^d → Θ(n^d), Θ(n^d log n) or Θ(n^(log_b a)).
  • Fast exponentiation: O(log n). Counting inversions: O(n log n) by piggybacking on merge sort.
  • Quickselect finds the k-th smallest in expected O(n); median-of-medians makes it worst-case O(n).
  • Karatsuba trades four sub-multiplications for three: Θ(n^1.585).

PDSA Interactive Book · Programming, Data Structures and Algorithms using Python (BSCS2002), IIT Madras BS Degree Programme.
Created by Ammar Hashmi · © 2026. An unofficial study companion — the syllabus follows the official course page and the examples are built around the PDSA Online Textbook; lectures by Prof. Madhavan Mukund (CMI). Always cross-check with the official course material.
Found a mistake or have a suggestion? Report it on GitHub ↗ · Press / to search.