Divide and conquer

Split, solve and combine · Part of Strategies

Key idea

Practice

6 questions · about 3 min

Explained step by step

Divide and conquer

Divide and conquer is a widely used strategy, almost always built with recursion, that has 2 stages. Divide: the problem is split into 2 or more subproblems, and those again, until the smallest ones are easy to solve. Conquer: starting from those small solutions, they are combined from the bottom up until the original problem is solved. Merge sort is the classic example: it splits down to pieces of 1 and merges back up.

To tell whether a problem fits divide and conquer, check 3 things. That it can be split into smaller problems of the same kind. That those subproblems are independent: they do not overlap or depend on each other. And that their solutions can be combined to solve the original. Merge sort meets all 3: the array splits in 2, each half sorts on its own, and 2 sorted halves merge.

Splitting can also make an algorithm more efficient. If bubble sort costs about n² steps, splitting the array into 2 halves, sorting each one and merging them costs about n²/2 + 2n: less than n² when n > 4. If you keep halving down to pieces of 1, you get merge sort, O(n log n). And if you split into k pieces at once, it looks like bucket sort.

Because divide and conquer produces independent subproblems, they can be solved at the same time on different processor cores or different computers. That does not change the complexity, but it cuts the real time a lot. For example, in bucket sort each bucket can be sorted on a different core and then joined.

Searches that cost O(log n) usually use divide and conquer. Binary search reduces searching the whole array to searching one half, and so on. It meets the conditions of being splittable and having independent subproblems, but there is nothing to combine: solving the remaining half already solves the problem. That is why it discards half of the candidates per step, while brute force discards 1.

Divide and conquer is in many places: merge sort, quick sort and bucket sort; binary search; search trees and heaps. It also solves classic problems: the closest pair of points, multiplying huge numbers with the Karatsuba algorithm, multiplying matrices with Strassen's, counting inversions or solving the Tower of Hanoi. Often it works in the background without being noticed.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Split, solve and combine