Algorithm Design Paradigms
Greedy choices, divide and conquer, backtracking and randomness.
Most problems have an obvious algorithm: try every possibility. For 20 booking requests that means about a million subsets to check, for 60 requests more than . Four ideas beat this explosion again and again: commit greedily, split and combine, explore but prune, and flip coins.
What you’ll learn
- Explain how greedy algorithms, divide and conquer, backtracking and randomization each beat brute force, and what each one risks.
- Test a greedy rule against the optimum, and refute a wrong rule with a single counterexample.
- Trace merge sort through its recursion tree and explain where its comes from.
- Describe backtracking as a walk through a tree of partial solutions, and explain how pruning shrinks that tree.
- Pick a paradigm from the signals in a problem statement.
Brute force, and four ways to beat it
Here is a problem you will meet in many disguises. A meeting room receives booking requests, each a time interval, and you must accept as many as possible with no two accepted meetings overlapping.
The algorithm that needs no insight is brute force: try every subset of the requests, throw away the subsets with a clash, and keep the largest one left. It is obviously correct. It is also hopeless beyond a few dozen requests, because every extra request doubles the number of subsets.
Brute force checks subsets for 10 requests. How many subsets must it check for 20 requests?
Show the answer
1048576 subsets
Each request is either in or out, so requests give subsets: , a thousand times more than , not twice as many. At 60 requests it is . At subsets per second (a rule of thumb for simple operations in a compiled language), that takes about 365 years.
Algorithm design is largely the art of not doing that. Four paradigms recur across this whole course. Each one exploits some structure of the problem to skip most of the possibilities, and each comes with a catch:
| Paradigm | The idea | Example | The catch |
|---|---|---|---|
| Greedy | Build the answer one choice at a time, always taking the choice that looks best right now, and never reconsider. | Accept the meeting that ends first; repeat. | Often wrong. It needs a proof. |
| Divide and conquer | Split the input into independent parts, solve each part recursively, combine the answers. | Merge sort. | Combining must be cheap, and the parts must not overlap. |
| Backtracking | Build candidates choice by choice, and abandon a partial candidate the moment it cannot succeed. | Placing queens on a chessboard. | Still exponential in the worst case. |
| Randomization | Let coin flips make some of the choices, so that no fixed input is always bad. | Quicksort with random pivots. | Guarantees hold on average over the coin flips, not on every run. |
Greedy: commit to the best-looking choice
A greedy algorithm makes a sequence of choices, each one the best by some simple local rule, and never takes a choice back. For the booking problem, known as interval scheduling, several rules sound reasonable. Accept the request that
- starts earliest, or
- is shortest, or
- has the fewest conflicts with the other requests, or
- finishes earliest.
After each choice, discard every request that overlaps it, and repeat until none is left. Each rule takes about time instead of . But do they find the best schedule?
One long early meeting fools the earliest-start rule: by accepting it, the rule blocks five short meetings. Other instances, built the same way, defeat shortest first and fewest conflicts. Earliest finish survives every instance, and the reason fits in two sentences.
The meeting that ends first leaves the room free as early as possible. If a best schedule starts with some other meeting, swap that meeting for the earliest-finishing one: it ends no later, so it clashes with nothing that came after, and the schedule keeps its size. Repeat the argument on the requests that remain.
On the requests , , , , , , , shortest first accepts , and , three meetings. Yet is a valid schedule of four. What does this single instance prove?
- Nothing yet: one bad instance could be bad luck in breaking ties
- Shortest first usually fails, so it should be avoided on large inputs
- Shortest first is not a correct algorithm for this problem
- No greedy rule can solve this problem, so brute force is needed
Show the answer
C. Shortest first is not a correct algorithm for this problem
An algorithm is correct only if it is right on every input, so one instance where it loses refutes it for good. The instance says nothing about how often the rule fails, and nothing against other rules: earliest finish solves this instance and every other one.
When greedy goes wrong
Paying an amount with the fewest coins, the coin change problem, looks like a textbook greedy problem: take the largest coin that fits, and repeat. With US coins (1, 5, 10 and 25 cents) this always gives the fewest coins. Now try a different coin system.
Greedy pays 6 as , three coins, while needs only two. Grabbing the 4 looked best and spoiled the rest. With coins 1, 3 and 4 greedy loses on 24 of the amounts from 1 to 99. Coin systems on which greedy never loses are called canonical. For the others, and for arbitrary coins in general, the fewest-coins problem needs dynamic programming.
How to spot a greedy problem. You build the answer by repeatedly picking among items; there is a natural order to pick them in (by end time, deadline, size or value per unit); and you can argue that the first pick is always safe. "Keep the largest set of non-overlapping intervals" is the archetype: sort by end time, then take greedily.
Look-alikes that need dynamic programming instead: the fewest coins for arbitrary denominations, and the 0/1 knapsack (pack whole items of the greatest total value into a bag of limited capacity).
Divide and conquer: split, solve, combine
Divide and conquer solves a problem by splitting it into smaller instances of the same problem, solving those recursively, and combining their answers. Merge sort is the model:
- divide: split the array into two halves;
- conquer: sort each half recursively (an array of one element is already sorted: the base case);
- combine: merge the two sorted halves by repeatedly moving the smaller of their two front elements to the output.
Why is this fast? Look at the recursion tree. The top call merges elements, the two calls below it merge each, the four below those each. Every level merges elements in total, and the sizes reach 1 after halvings. So merge sort does about steps of merging, while comparing every pair of elements, the brute-force way to put things in order, takes about comparisons.
Merge sort splits items in halves, again and again, until only single items remain. How many levels of halving is that?
Show the answer
20 levels
Each level halves the size: takes 20 halvings. So merge sort moves each item about 20 times, roughly steps in all, while comparing all pairs would take about comparisons.
How to spot divide and conquer. The answer for the whole can be assembled from the answers for two halves plus something about where they meet: a merge, a count of pairs that straddle the middle, the best solution that crosses the midpoint. Sorting, counting inversions (pairs that are out of order) and finding the closest pair of points all fit. The look-alike: if the parts overlap, divide and conquer repeats work. Naive recursive Fibonacci makes 331,160,281 calls to compute from just 41 distinct values, a job for dynamic programming.
Backtracking: explore every choice, prune dead ends
Some problems really do ask for every possibility: list all subsets, all orders, all ways to place pieces on a board. Backtracking enumerates them systematically, one choice at a time: choose an option, explore everything that follows from it, then un-choose it and try the next option. The partial solutions form a tree, the state-space tree, and backtracking walks it depth first.
So far this is brute force with tidy bookkeeping. The power comes from pruning: as soon as a partial solution breaks a rule, abandon it, and with it every way of completing it. The n-queens puzzle asks for queens on an board, one per row, with no two sharing a column or a diagonal. Placing all 4 queens and only then checking means testing full boards. Checking each queen as it is placed kills most branches after one or two queens.
How to spot backtracking. The problem says all, every or list each, or asks whether any arrangement satisfies a set of rules, and the input is small. As a rule of thumb, about 10 items when the answers are orders ( of them) and 20 to 25 when they are subsets (). Sudoku, n-queens, generating permutations and choosing numbers with a target sum are the classics. The look-alike: if you only need to count the solutions or find the best one, and the same subproblems keep recurring, dynamic programming may finish in polynomial time.
Randomization: no input is always bad
Quicksort picks a pivot, moves the smaller elements to its left and the larger ones to its right, and recurses on both sides. With the last element as the pivot, a random array sorts quickly. An already sorted array is a disaster: every pivot is the largest element, every partition peels off nothing but the pivot, and the comparisons add up to .
A random pivot is unlikely to be extreme, so no particular input can force the bad case. For every input, sorted or not, the expected number of comparisons is about for large , and quadratic time needs an absurdly long run of bad luck. The guarantee has moved from the input to the algorithm's own coin flips.
How to spot randomization. Some input order, or an adversary choosing inputs, can make a deterministic method slow: think quicksort on sorted data, or a hash table flooded by keys picked to collide. Or the data is too large to examine exactly, and a random sample answers well enough. Randomness is also the simplest tie-breaker against worst cases you did not anticipate.
Choosing a paradigm
Faced with a new problem, write down the brute force first, then ask which structure lets you skip most of it:
| If the problem… | Try | Because |
|---|---|---|
| asks for the most non-overlapping intervals, the fewest items covering something, or has a natural order (deadline, end time, ratio) | Greedy | one locally best choice can be proved safe |
| has an answer for the whole that combines answers for halves: sorting, counting pairs, closest points | Divide and conquer | the halves are independent and combining is cheap |
| says "list all" or "is there any arrangement", with up to about 20 | Backtracking with pruning | the search is exponential anyway, so cut every dead branch early |
| suffers from bad input orders or adversaries, or only needs an estimate from huge data | Randomization | no fixed input is bad for random choices |
| counts or optimizes over choices whose subproblems repeat | Dynamic programming | each distinct subproblem is solved only once |
A lecture hall must host a list of exams, each with a start and an end time. You may cancel exams, and you want to keep as many as possible with no two overlapping. There are up to exams. Which approach fits?
- Backtracking over subsets of exams, pruning any subset with a clash
- Sort the exams by end time and keep each exam that starts after the last kept one ends
- Split the exams into morning and afternoon halves, solve each half, and combine
- Shuffle the exams randomly and keep each one that still fits
Show the answer
B. Sort the exams by end time and keep each exam that starts after the last kept one ends
This is interval scheduling in disguise, and earliest finish is optimal: for the sort plus one pass. Recognizing the disguise is most of the work.
| Optimized lesson | What you will do there |
|---|---|
| Greedy Algorithms | Prove greedy algorithms correct with "greedy stays ahead" and exchange arguments, schedule jobs against deadlines, and recognize the greedy problems of interviews and contests. |
| Divide and Conquer | Turn a split-and-combine algorithm into a recurrence and solve it, count inversions in , and see when overlapping halves call for dynamic programming. |
| Backtracking | Write the choose, explore, un-choose template; generate subsets, permutations and combinations; solve n-queens and sudoku; skip duplicate branches. |
| Randomized Algorithms | Tell Las Vegas from Monte Carlo algorithms, boost a success probability by repetition, and check a matrix product with random vectors. |
Key takeaways
- Brute force is the baseline: correct, simple, and usually exponential ( subsets, orders). Each paradigm exploits structure to skip most of it.
- Greedy commits to the locally best choice and never looks back: fast, but correct only with a proof. Earliest finish is optimal for interval scheduling; largest coin first fails for coins 1, 3 and 4.
- Divide and conquer splits into independent subproblems and combines their answers: merge sort does work on each of about levels.
- Backtracking walks the tree of partial solutions depth first (choose, explore, un-choose), and pruning cuts a branch as soon as it cannot succeed: 4 queens shrinks from 341 nodes to 17.
- Randomization makes guarantees hold in expectation for every input: random pivots defeat the sorted input that ruins last-element quicksort.
- Read the signals: non-overlapping intervals point to greedy, combinable halves to divide and conquer, "list all" with small to backtracking, bad input orders to randomization, shared subproblems to dynamic programming.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
With coins 1, 7 and 10, greedy pays 14 as . How many more coins than necessary is that?
- None: greedy is optimal for every coin system that contains a 1
- 1
- 3
- It depends on the order in which the coins are tried
Show the answer
C. 3
uses two coins, and greedy uses five, so three more. Taking the 10 first leaves 4, which only 1s can pay.
Each level of merge sort's recursion tree merges elements in total. Why is merge sort's total work about rather than ?
- Merging is free once the two halves are sorted
- Each level merges fewer elements than the level above it
- Merge sort skips the work when the input is already sorted
- The sizes halve at every level, so there are only about levels
Show the answer
D. The sizes halve at every level, so there are only about levels
The subarray sizes go , so the tree has about levels, and each level does work. For a million items that is about 20 levels, against the half a trillion pairs a brute-force comparison of all pairs would examine.
A backtracking search lists all subsets of 5 items, deciding one item per level (include it or exclude it). How many leaves does its tree have, and how many nodes in total?
- 5 leaves, 15 nodes
- 32 leaves, 63 nodes
- 25 leaves, 31 nodes
- 120 leaves, 326 nodes
Show the answer
B. 32 leaves, 63 nodes
Level has nodes, so the leaves at level 5 number , one per subset, and the tree has nodes.
Why is it safe for backtracking to abandon a partial n-queens board as soon as two of its queens attack each other?
- Adding more queens can never remove an attack, so no completion of that board is a solution
- Such boards are rare, so skipping them barely changes the answer
- The search only needs one solution, so it may skip some
- It is not safe: pruning trades correctness for speed
Show the answer
A. Adding more queens can never remove an attack, so no completion of that board is a solution
A constraint that is already broken stays broken whatever is added later, so the whole subtree below that board contains no solution. Pruning it loses nothing, and the search still finds every solution.
Randomized quicksort picks each pivot uniformly at random. Which statement is true?
- It can never take quadratic time
- Its expected number of comparisons is on every input, sorted inputs included
- It is fast on random inputs but still slow on sorted inputs
- With small probability it returns an array that is not sorted
Show the answer
B. Its expected number of comparisons is on every input, sorted inputs included
The expectation is over the algorithm's own coin flips, so it holds for each input separately, including the sorted input that ruins the last-element pivot. Quadratic time is still possible, but only after an extremely unlikely run of bad pivots.
Go deeper
- Greedy Algorithms · Take the best-looking step and never look back, and prove when that works.
- Divide and Conquer · Split the problem, solve the parts, combine the answers.
- Backtracking · Build a solution one choice at a time, and undo the dead ends.
- Randomized Algorithms · Coin flips that make algorithms simpler, faster, or both.
Further reading
- J. Kleinberg & É. Tardos, Algorithm Design (Addison-Wesley, 2005), chapters 4 (greedy algorithms), 5 (divide and conquer) and 13 (randomized algorithms).
- J. Erickson, Algorithms (2019, free online), chapters 1 (recursion and divide and conquer), 2 (backtracking) and 4 (greedy algorithms).