O(n) linear time
easy 13 minO(n) means the work grows in direct proportion to the input: double the data, double the time.
Video lesson · Chapter 1 of 5
Which tray first runs dry?
O(n) linear time
1:25Reel
Read caption
Pia scans six unsorted weights, tracks the maximum, and counts comparisons. Every pearl gets on the scale.
How it works
Step through the idea, or press Play.
Visit each element. One pass from the first element to the last, touching each one once or a constant number of times
Understand it
Start here
What O(n) means
An algorithm is O(n), or linear, when the number of operations grows in direct proportion to the input size . Double the input and the time doubles. Each element is visited once, or a fixed number of times, and the work per visit does not depend on .
Proportional
10 times the data takes 10 times the time. The growth is a straight line.
Each element once
One pass over the data, or a constant number of passes, with work per element.
Often optimal
If the answer depends on every element, you must read all of them. Nothing beats then.
The shape of a linear cost
The picture
The single loop pattern
One pass over n elements
def process_all(arr): ops = 0 for x in arr: # n iterations ops += 1 # constant-time work return opsfor n in [10, 100, 1000]: print(n, process_all(list(range(n))))The math
Why constants drop
Big O describes how the cost grows, not its exact size. A loop that does 3 operations per element plus 5 for setup costs . For large the hardly matters, and the factor 3 depends on the machine and the language, not on the algorithm. Both are dropped.
The formal definition, checked
Simplifying a cost to its class
| Exact cost | Where it comes from | Class |
|---|---|---|
| Find max: compare every element after the first | ||
| Sum: one addition per element | ||
| Reverse in place: swap pairs | ||
| Linear search, average case | ||
| Two separate passes over the data |
Scale
How linear growth feels
| n | operations | Time at 1 μs each |
|---|---|---|
| 100 | 100 | 0.1 ms |
| 1,000 | 1,000 | 1 ms |
| 10,000 | 10,000 | 10 ms |
| 1,000,000 | 1,000,000 | 1 second |
| 1,000,000,000 | 1,000,000,000 | about 17 minutes |
Doubling the input
n against its neighbours
| n | |||
|---|---|---|---|
| 8 | 3 | 8 | 64 |
| 100 | about 7 | 100 | 10,000 |
| 1,000 | about 10 | 1,000 | 1,000,000 |
| 1,000,000 | about 20 | 1,000,000 | (about 11.6 days at 1 μs) |
Example 1
Finding the maximum (and minimum)
Find max in one pass
x < min for the minimum.def find_max(arr): max_val = arr[0] ops = 0 for x in arr[1:]: ops += 1 if x > max_val: max_val = x return max_val, opsprint(find_max([3, 7, 2, 9, 4, 1, 8, 5])) # (9, 7)print(find_max([3, 7, 2, 9, 4])) # (9, 4)print(find_max([-4, -9, -2])) # (-2, 2)Exactly how many comparisons
Example 2
Linear search: best, average and worst case
Linear search
| Case | When it happens | Checks | Class |
|---|---|---|---|
| Best | Target is the first element | 1 | |
| Average | Target present, any position equally likely | ||
| Worst | Target is last, or not there at all |
The average case
Example 3
Sum, count and average
Aggregates need every element, because each one contributes to the result. Summing [3, 7, 2, 9, 4, 1, 8, 5] takes 8 additions: the total runs 3, 10, 12, 21, 25, 26, 34, 39. Start the total at 0, the identity for addition.
def sum_array(arr): total = 0 for x in arr: # n additions total += x return totaldef count_greater(arr, limit): return sum(1 for x in arr if x > limit)arr = [3, 7, 2, 9, 4, 1, 8, 5]print(sum_array(arr)) # 39print(count_greater(arr, 4)) # 4 (7, 9, 8, 5)print(sum_array(arr) / len(arr)) # 4.875Common O(n) operations
Min and max
Must check every element: the extreme might be the last one.
Linear search
Check each element until found. Worst case, not present: all .
Sum, count, average
Aggregates need every element, since each contributes to the result.
Two pointers
Each pointer crosses the array at most once, so in total.
Several passes
Two passes, two pointers, still linear
Passes add, they do not multiply
def reverse_in_place(arr): left, right = 0, len(arr) - 1 swaps = 0 while left < right: arr[left], arr[right] = arr[right], arr[left] left += 1 right -= 1 swaps += 1 return swapsdata = [3, 7, 2, 9, 4, 1, 8, 5]print(reverse_in_place(data), data) # 4 [5, 8, 1, 4, 9, 2, 7, 3]Still O(n)
- Two separate loops over the data, one after the other.
- Two pointers that only move toward each other.
- One pass plus a hash set with average lookups.
Not O(n) any more
- A loop inside a loop over the same data: .
x in some_listorlist.index(x)inside a loop.list.insert(0, x)orlist.pop(0)inside a loop.
Comparison
O(n) next to its neighbours
| Class | What it looks like | Examples |
|---|---|---|
| , faster | Direct access, no iteration | arr[i], a hash lookup, len(arr) |
| , faster | Halve the work each step | Binary search on sorted data |
| , you are here | A single pass through the data | Find max, sum, linear search |
| , slower | Linear work at each of levels | Merge sort, sorting in general |
| , slower | A nested loop over the data | Bubble sort, brute-force pair checks |
def two_sum(arr, target): seen = {} # value -> index for i, x in enumerate(arr): if target - x in seen: # O(1) average lookup return seen[target - x], i seen[x] = i return Noneprint(two_sum([3, 7, 2, 9, 4, 1, 8, 5], 13)) # (3, 4): 9 + 4Pattern spotting
Spotting O(n) in code
| Code shape | What it is | Cost |
|---|---|---|
for i in range(n): | Single loop through n elements | |
for x in arr: | Iterate each element once | |
while left < right: | Two pointers moving toward the centre | |
seen = {} then if x in seen | One pass with hash map lookups | |
sum(arr), max(arr), min(arr) | Built-in aggregations | |
for i ...: for j ...: | Nested loops over the data | , not linear |
Is this code O(n)?
in on a list, index, insert(0, x), slicing.In the wild
Where O(n) runs
Log scanning
grepand log search tools read every line once to find matches.Full table scans
A database query on a column with no index reads every row: .
Checksums and hashes
Hashing a file reads every byte once, so time grows with the file size.
Streaming stats
Running totals, minimums and maximums over sensor readings, one value at a time.
Deduplication
One pass with a hash set removes repeats from a list of emails or IDs.
Spreadsheet totals
SUMover a column touches every cell in the range once.
Recap
Key takeaways
Key points
- O(n) means work grows in proportion to the input: double the data, double the time.
- : constants and lower terms drop, so , and are all linear.
- A single loop with work per element is ; passes in sequence add, nested loops multiply.
- Find max takes comparisons and sum takes additions: both and both optimal.
- Linear search: best , average , worst . Quote the worst case, .
- Watch for hidden linear calls inside a loop (
inon a list,insert(0, x)), which make it .