O(n²) -- Quadratic Time
Quadratic code does work in proportion to n × n. Doubling the rows quadruples the steps, and 10 times the rows means 100 times the steps. It survives testing because sample data is small enough that even n × n steps finish quickly.
A loop inside a loop
The plainest quadratic shape is a loop whose body holds a second loop over the same input. For each of the n outer rows, the inner loop runs n times, so the innermost line runs n × n times.
def count_pairs(rows):
steps = 0
for a in rows:
for b in rows:
steps = steps + 1
return steps
print(count_pairs(list(range(10))))
print(count_pairs(list(range(20))))
print(count_pairs(list(range(40))))Output:
100 400 1600
Going from 10 rows to 20 took the steps from 100 to 400. Sometimes that is the job, such as comparing every pair of sensor readings. More often it arrives by accident, with the inner loop written as something that doesn't look like a loop.
The hidden inner loop
A common dedup remembers the ids it has kept in a list and checks each new id against that list:
def dedupe(event_ids):
seen = []
for event_id in event_ids:
if event_id not in seen:
seen.append(event_id)
return seenIt reads as a single loop. On a list, though, event_id not in seen walks seen from the front, and seen grows as the function runs. The animation writes that hidden walk out as a real inner loop so you can watch the comparisons pile up.
event_ids = ["e1", "e2", "e3", "e2", "e4"]
seen = []
checks = 0
for event_id in event_ids:
found = False
for old_id in seen:
checks = checks + 1
if old_id == event_id:
found = True
break
if not found:
seen.append(event_id)
print(seen)
print("checks:", checks)['e1', 'e2', 'e3', 'e4'] checks: 8
With all-unique ids, each walk is 1 comparison longer than the last, so the total comes to about n² / 2. For 1,000 events that is 499,500 comparisons. For 1,000,000 events it is about 500 billion, and half of n² is still quadratic.
The fix: let a set do the remembering
def dedupe(event_ids):
seen = set()
unique = []
for event_id in event_ids:
if event_id not in seen:
seen.add(event_id)
unique.append(event_id)
return uniqueThe set answers event_id not in seen in constant time however many ids it holds, so the loop is n iterations of fixed work: O(n). The list unique stays because it keeps ids in their arrival order, which a set does not promise. At 1,000,000 events, about 500 billion comparisons become about 1 million hash lookups.
Other one-liners that hide a loop
An O(n) call inside a loop over n rows is O(n²)
- values.count(x) inside a loop: each call compares every item in the list.
- max(values) inside a loop over values: recomputes the same answer on every row. Compute it once, before the loop.
- rows.remove(row) inside a loop: each removal searches the list, then shifts everything after the gap.
- rows.insert(0, row) inside a loop: each insert shifts every item already in the list.
Matching 2 inputs: O(n × m)
Matching rows from 2 different inputs follows the same rule with 2 letters. Matching each of n plays to an artist by searching a list of m artists costs up to n × m comparisons. With 1,000,000 plays and 50,000 artists, that is 50 billion. Build a dict from the artist list once (m steps), then look each play up in it (n steps), and the job costs n + m.
To find the trap in any loop, go line by line and ask whether that line's cost depends on how many rows came before it. In the list-based dedup, only the membership check does:
| line inside the loop | with a list | with a set |
|---|---|---|
| the loop itself | n iterations | n iterations |
| `event_id not in seen` | grows with `seen`: O(n) | 1 hash lookup: O(1) |
| remembering the id | `seen.append(event_id)`: O(1) | `seen.add(event_id)`: O(1) |
Only the growing line needs changing. Reordering the statements or rewriting the loop and the appends leaves the growth rate untouched, because each of them already costs a constant per row.
Which change turns this function from O(n²) into O(n)?
def flag_repeat_users(user_ids):
earlier = []
repeats = []
for user in user_ids:
if user in earlier:
repeats.append(user)
earlier.append(user)
return repeats- Start earlier as set() and call earlier.add(user) instead of append
- Start repeats as set() so repeated users are stored without duplicates
- Replace the for loop with a while loop that walks the list by index
- Move earlier.append(user) above the if so the list fills sooner
About this lesson
This section is part of the Complexity: Beginner 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.