Divide-and-Conquer and Greedy
Two design patterns sit behind many of the fast algorithms you already use. Divide and conquer splits the input, solves each part recursively and combines the answers. Greedy takes the choice that looks best right now, commits to it and never revisits it. You can read each one's cost off its structure, but greedy carries a risk that divide and conquer avoids: a fast answer that is wrong.
Split, solve, combine
Merge sort is the standard case. A list of 1 item is already sorted, and 2 sorted lists merge into 1 in a single pass that walks a pointer through each, the two-pointer technique applied to merging.
def merge_sort(rows):
if len(rows) <= 1:
return rows
mid = len(rows) // 2
left = merge_sort(rows[:mid])
right = merge_sort(rows[mid:])
merged = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged += left[i:] + right[j:]
print("merged", merged)
return merged
print(merge_sort([7, 3, 9, 1, 4]))merged [3, 7] merged [1, 4] merged [1, 4, 9] merged [1, 3, 4, 7, 9] [1, 3, 4, 7, 9]
Reading the cost off the recursion
Three facts set the cost: how many parts each call makes, their size, and the price of the combine step. Merge sort makes 2 halves and merges in O(n), so each recursion level touches all n items once, and halving reaches size 1 after about log2 n levels: O(n log n). For 1 million rows that is 20 levels deep, far inside Python's default recursion limit of 1,000.
| Pattern | Parts per call | Combine step | Total |
|---|---|---|---|
| Binary search | 1 half | O(1) | O(log n) |
| Max of a range by halves | 2 halves | O(1) | O(n) |
| Merge sort | 2 halves | O(n) | O(n log n) |
| Peel off 1 item, recurse on the rest | 1 part of size n - 1 | O(n) | O(n²) |
The last row is the trap: peeling off 1 item per call gives n levels instead of log n. Sorting data bigger than memory reuses the merge step: sort chunks that fit, then stream the sorted runs through heapq.merge at O(log k) per row for k runs.
What is the time complexity of peak(values, 0, len(values)) on a list of n values?
def peak(values, lo, hi):
if hi - lo == 1:
return values[lo]
mid = (lo + hi) // 2
return max(peak(values, lo, mid), peak(values, mid, hi))- O(log n), because each call halves the range it looks at
- O(n log n), because the recursion is log n levels deep
- O(n²), because max compares every pair of values
- O(n), because about 2n calls each do O(1) work
Greedy: commit and never look back
One shared compute slot, 5 maintenance jobs with start and end hours, and the goal is to run as many as possible without overlap. A greedy scheduler sorts the jobs, takes each one that starts after the slot frees up, and skips the rest. The sort key is the entire algorithm.
jobs = [("backfill", 1, 9), ("compact", 2, 4), ("vacuum", 4, 6),
("export", 5, 8), ("audit", 8, 10)]
def schedule(jobs, key):
chosen, free_at = [], 0
for name, start, end in sorted(jobs, key=key):
if start >= free_at:
chosen.append(name)
free_at = end
return chosen
print(schedule(jobs, key=lambda job: job[1]))
print(schedule(jobs, key=lambda job: job[2]))Output:
['backfill'] ['compact', 'vacuum', 'audit']
Sorting by start time grabs backfill first, which holds the slot from hour 1 to hour 9 and blocks every other job. Sorting by end time is provably optimal: the job that finishes first leaves the most room afterward, and any best schedule can swap its first job for that one without losing a job. Repeating that swap down the schedule is an exchange argument, the usual proof behind a greedy rule. Cost: O(n log n) to sort plus 1 O(n) pass.
When the locally best choice is wrong
A bulk-load API accepts batches of exactly 25, 10, 5 or 1 rows and bills per request. Greedy keeps sending the largest batch that fits.
def greedy_batches(rows, sizes):
batches = []
for size in sorted(sizes, reverse=True):
while rows >= size:
rows -= size
batches.append(size)
return batches
print(greedy_batches(63, [25, 10, 5, 1]))
print(greedy_batches(6, [4, 3, 1]))Output:
[25, 25, 10, 1, 1, 1] [4, 1, 1]
For sizes 25, 10, 5 and 1, greedy happens to be optimal. Switch to 4, 3 and 1 and it sends 3 requests for 6 rows where 2 batches of 3 suffice. With arbitrary sizes, the fewest-requests answer needs memoized recursion over every row total from 1 to the target, costing O(target × sizes). Before trusting a greedy rule, compare it with brute force on a few hundred small inputs: 1 mismatch settles the question.
About this lesson
This section is part of the Complexity: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.