AlgoViz

O(n) linear time

easy 13 min

O(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?

0:00 / 4:17

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.

Step 1 of 3

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 nn. 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 nn.

  • 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 O(1)O(1) work per element.

  • Often optimal

    If the answer depends on every element, you must read all nn of them. Nothing beats O(n)O(n) then.

The shape of a linear cost

T(n)=c⋅n+d  ∈  O(n)T(n) = c \cdot n + d \;\in\; O(n)
cc is the cost of the work done per element and dd is the fixed setup cost. Whatever their values, the total grows like nn.

The picture

The single loop pattern

One pass over n elements

The loop test runs n+1n + 1 times and the body nn times. With constant work in the body, the total is O(n)O(n).
Python
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))))
Count the loop rounds: 10 items, 10 rounds; 1,000 items, 1,000 rounds.
Edit and run it in your browser

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 3n+53n + 5. For large nn the +5+5 hardly matters, and the factor 3 depends on the machine and the language, not on the algorithm. Both are dropped.

The formal definition, checked

3n+5≤4nfor all n≥5  ⟹  3n+5∈O(n)(c=4, n0=5)3n + 5 \le 4n \quad \text{for all } n \ge 5 \;\Longrightarrow\; 3n + 5 \in O(n) \quad (c = 4,\ n_0 = 5)
f(n)∈O(g(n))f(n) \in O(g(n)) means some constant cc and starting point n0n_0 exist with f(n)≤c⋅g(n)f(n) \le c \cdot g(n) for every n≥n0n \ge n_0. One straight line above another, from some point on.

Simplifying a cost to its class

The same two moves turn n−1n - 1, n/2n/2 and 2n+1002n + 100 into O(n)O(n).
Exact costWhere it comes fromClass
n−1n - 1Find max: compare every element after the firstO(n)O(n)
nnSum: one addition per elementO(n)O(n)
n/2n / 2Reverse in place: swap n/2n/2 pairsO(n)O(n)
(n+1)/2(n + 1) / 2Linear search, average caseO(n)O(n)
2n2nTwo separate passes over the dataO(n)O(n)
Different constants, the same straight-line growth.

Scale

How linear growth feels

nO(n)O(n) operationsTime at 1 μs each
1001000.1 ms
1,0001,0001 ms
10,00010,00010 ms
1,000,0001,000,0001 second
1,000,000,0001,000,000,000about 17 minutes
Every extra factor of 10 in nn costs exactly a factor of 10 in time.

Doubling the input

T(2n)=c⋅2n=2⋅T(n)vs(2n)2=4n2T(2n) = c \cdot 2n = 2 \cdot T(n) \qquad \text{vs} \qquad (2n)^2 = 4n^2
Linear work doubles when nn doubles. Quadratic work quadruples. That gap is why a single pass beats a nested loop so badly at scale.

n against its neighbours

nlog⁡2n\log_2 nnnn2n^2
83864
100about 710010,000
1,000about 101,0001,000,000
1,000,000about 201,000,000101210^{12} (about 11.6 days at 1 μs)
At a million items, linear takes a second and quadratic takes almost two weeks.

Example 1

Finding the maximum (and minimum)

Find max in one pass

One comparison per element after the first. Flip the test to x < min for the minimum.
Python
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)
[3, 7, 2, 9, 4, 1, 8, 5]: max goes 3, 7, 9 and stays. 8 elements, 7 comparisons.
Edit and run it in your browser

Exactly how many comparisons

comparisons=n−1∈O(n)n=8⇒7\text{comparisons} = n - 1 \in O(n) \qquad n = 8 \Rightarrow 7
The first element becomes the starting max, so it is never compared. Tracking min and max together costs 2(n−1)2(n - 1), still O(n)O(n).

Example 2

Linear search: best, average and worst case

Linear search

It can stop early when it finds the target, which is what separates the best case from the worst.
CaseWhen it happensChecksClass
BestTarget is the first element1O(1)O(1)
AverageTarget present, any position equally likely(n+1)/2(n + 1)/2O(n)O(n)
WorstTarget is last, or not there at allnnO(n)O(n)
In [3, 7, 2, 9, 4, 1, 8, 5], finding 4 takes 5 checks, 3 takes 1 and the missing 6 takes all 8.

The average case

E[checks]=1n∑k=1nk=1n⋅n(n+1)2=n+12∈O(n)\mathbb{E}[\text{checks}] = \frac{1}{n}\sum_{k=1}^{n} k = \frac{1}{n} \cdot \frac{n(n+1)}{2} = \frac{n+1}{2} \in O(n)
On average the search looks at about half the array. Half is a constant factor, so the average case is still linear. A search over 1,000 items needs at most 1,000 checks.

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.

Python
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.875
Sum, count above a threshold and average: one pass each, n operations each.
Edit and run it in your browser

Common 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 nn.

  • Sum, count, average

    Aggregates need every element, since each contributes to the result.

  • Two pointers

    Each pointer crosses the array at most once, so O(n)O(n) in total.

Several passes

Two passes, two pointers, still linear

Passes add, they do not multiply

O(n)+O(n)+O(n)=O(3n)=O(n)butO(n)×O(n)=O(n2)O(n) + O(n) + O(n) = O(3n) = O(n) \qquad \text{but} \qquad O(n) \times O(n) = O(n^2)
Loops one after another add their costs. Only a loop nested inside another multiplies them.
Python
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]
Reverse in place: the two pointers meet in the middle after n/2n/2 swaps, so O(n)O(n) time and O(1)O(1) extra space.
Edit and run it in your browser

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 O(1)O(1) average lookups.

Not O(n) any more

  • A loop inside a loop over the same data: O(n2)O(n^2).
  • x in some_list or list.index(x) inside a loop.
  • list.insert(0, x) or list.pop(0) inside a loop.

Comparison

O(n) next to its neighbours

ClassWhat it looks likeExamples
O(1)O(1), fasterDirect access, no iterationarr[i], a hash lookup, len(arr)
O(log⁡n)O(\log n), fasterHalve the work each stepBinary search on sorted data
O(n)O(n), you are hereA single pass through the dataFind max, sum, linear search
O(nlog⁡n)O(n \log n), slowerLinear work at each of log⁡n\log n levelsMerge sort, sorting in general
O(n2)O(n^2), slowerA nested loop over the dataBubble sort, brute-force pair checks
Python
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 + 4
One pass with a hash map: O(n)O(n) instead of checking all n(n−1)/2n(n-1)/2 pairs.
Edit and run it in your browser

Pattern spotting

Spotting O(n) in code

Code shapeWhat it isCost
for i in range(n):Single loop through n elementsO(n)O(n)
for x in arr:Iterate each element onceO(n)O(n)
while left < right:Two pointers moving toward the centreO(n)O(n)
seen = {} then if x in seenOne pass with hash map lookupsO(n)O(n)
sum(arr), max(arr), min(arr)Built-in aggregationsO(n)O(n)
for i ...: for j ...:Nested loops over the dataO(n2)O(n^2), not linear

Is this code O(n)?

Watch for hidden linear calls in the body: in on a list, index, insert(0, x), slicing.

In the wild

Where O(n) runs

  • Log scanning

    grep and 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: O(n)O(n).

  • 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

    SUM over 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.
  • T(n)=c⋅n+d∈O(n)T(n) = c \cdot n + d \in O(n): constants and lower terms drop, so n−1n - 1, n/2n/2 and 3n+53n + 5 are all linear.
  • A single loop with O(1)O(1) work per element is O(n)O(n); passes in sequence add, nested loops multiply.
  • Find max takes n−1n - 1 comparisons and sum takes nn additions: both O(n)O(n) and both optimal.
  • Linear search: best O(1)O(1), average (n+1)/2(n + 1)/2, worst nn. Quote the worst case, O(n)O(n).
  • Watch for hidden linear calls inside a loop (in on a list, insert(0, x)), which make it O(n2)O(n^2).

Sources