O(n) -- Linear Time
A linear-time job visits each row once and does a fixed amount of work per visit, so 10 times the rows means 10 times the steps and no more. For a job that must read every record, that's the best growth rate on offer: no code can total revenue across 50 million orders without looking at all 50 million.
A single pass with constant work per row
The pattern is a for loop over the input where every operation inside is O(1). The body may do arithmetic and comparisons, read or write a dict, check a set or call append. The cost is n rows times a fixed cost per row, which grows in step with n.
Most pipeline code aggregates rows into a dict. Each play adds its seconds to its artist's running total. Watch the dict fill as the loop moves down the list.
plays = [
["Nova", 210],
["Rook", 185],
["Nova", 240],
["Ivy", 199],
["Rook", 60],
]
totals = {}
steps = 0
for play in plays:
artist = play[0]
seconds = play[1]
if artist in totals:
totals[artist] = totals[artist] + seconds
else:
totals[artist] = seconds
steps = steps + 1
print(totals)
print("rows:", len(plays), "steps:", steps){'Nova': 450, 'Rook': 245, 'Ivy': 199}
rows: 5 steps: 5
The loop ran 5 times for 5 rows. Each iteration did a membership check and a dict write along with a couple of additions. All of that is constant time, so the job is O(n). Feed it 5 million plays and it runs 5 million iterations, while the dict only grows to the number of distinct artists.
Built-ins that loop for you
Some one-line calls hide a full pass over their input. sum(values) reads every item, and so do min(values) and max(values), which makes each of them O(n). set(values) and list(values) copy every item, also O(n). A list's in check is a pass that can stop early. len(values) is the exception: the list stores its own length, so asking for it is O(1).
Calling several of these one after another keeps the job linear. summarize below makes 3 passes over the same list for about 3n steps. Double the rows and the steps still only double.
def summarize(seconds_played):
total = sum(seconds_played)
longest = max(seconds_played)
shortest = min(seconds_played)
return [total, longest, shortest]A loop stays linear only while everything inside it is constant time. Put an O(n) call inside the loop and the job does n passes of n steps each, which is the trap the next section hunts down.
Several answers from one pass
A single loop can keep several running results at once, each in its own variable started before the loop. This pass over 6 play durations counts skips, meaning plays under 30 seconds, and tracks the longest play.
durations = [212, 14, 187, 9, 240, 31]
skips = 0
longest = 0
for seconds in durations:
if seconds < 30:
skips = skips + 1
if seconds > longest:
longest = seconds
print("skips:", skips)
print("longest:", longest)Output:
skips: 2 longest: 240
Each row costs 2 comparisons and at most 2 assignments, so the loop stays O(n) whether it reads 6 rows or 6 million. A third running result would add a constant amount of work per row and leave the growth rate where it was.
Running results sometimes live in separate loops instead. Running 2 loops over the same rows, one after the other, costs the first pass plus the second. The table counts steps for 1 loop and for 2 sequential loops. The second pass doubles the count at every size, and going from 1,000 rows to 2,000 doubles both columns.
| rows (n) | 1 loop | 2 loops in sequence |
|---|---|---|
| 1,000 | 1,000 | 2,000 |
| 2,000 | 2,000 | 4,000 |
| 1,000,000 | 1,000,000 | 2,000,000 |
How does the work in report grow as rows grows?
def report(rows):
total = 0
for row in rows:
total = total + row
count = 0
for row in rows:
if row > 100:
count = count + 1
return [total, count]- O(n²), because the function contains 2 loops over rows
- O(1), because each loop body does a fixed amount of work
- O(n) for the first loop only, since the second loop exits early
- O(n), because the 2 passes add up to about 2n steps
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.