TExcelTAD
Home › Data Structures & Algorithms › Time Complexity & Big O

Time Complexity & Big O

How fast is an algorithm? Measuring seconds is unreliable: it depends on the computer, the language, other running programs and the specific input. Instead, we count basic operations (comparisons, assignments, array accesses) as a function of the input size n, and look at how that count grows as n gets large. That growth rate is the algorithm's time complexity.

Counting operations

Let's count the comparisons of three ways to work with a list of n numbers:

python · try it yourself
def find_max(values):              # look at each value once
    ops = 0
    best = values[0]
    for v in values[1:]:
        ops += 1
        if v > best:
            best = v
    return ops

def has_duplicate(values):         # compare every pair
    ops = 0
    for i in range(len(values)):
        for j in range(i + 1, len(values)):
            ops += 1
            if values[i] == values[j]:
                return ops
    return ops

def halvings(n):                   # how often can n be halved?
    ops = 0
    while n > 1:
        n //= 2
        ops += 1
    return ops

print(f"{'n':>6} {'find_max':>9} {'has_duplicate':>14} {'halvings':>9}")
for n in [10, 100, 1000, 10000]:
    data = list(range(n))          # no duplicates: the worst case
    print(f"{n:>6} {find_max(data):>9} {has_duplicate(data):>14} {halvings(n):>9}")
     n  find_max  has_duplicate  halvings
    10         9             45         3
   100        99           4950         6
  1000       999         499500         9
 10000      9999       49995000        13

Each time n grows tenfold, find_max does about 10 times more work, has_duplicate about 100 times more, and halvings only adds about 3 steps. These are three different complexity classes: linear, quadratic and logarithmic.

Big O notation

Big O describes the growth rate as an upper bound, ignoring details that don't matter for large n:

  • find_max makes n - 1 comparisons: O(n).
  • has_duplicate makes up to n(n-1)/2 = 0.5n² - 0.5n: O(n²).
  • halvings makes ⌊log₂ n⌋: O(log n).

Two rules turn an exact count into Big O:

  1. Keep only the fastest-growing term. For large n, 0.5n² dwarfs 0.5n.
  2. Drop constant factors. 0.5n² and 3n² are both O(n²); constants depend on hardware and implementation, while the growth rate does not.
python · try it yourself
for n in [10, 100, 1000, 10000]:
    exact = n * (n - 1) // 2
    print(f"n={n:>5}: n(n-1)/2 = {exact:>10,}   n²/2 = {n * n // 2:>10,}   ratio {exact / (n * n / 2):.4f}")
n=   10: n(n-1)/2 =         45   n²/2 =         50   ratio 0.9000
n=  100: n(n-1)/2 =      4,950   n²/2 =      5,000   ratio 0.9900
n= 1000: n(n-1)/2 =    499,500   n²/2 =    500,000   ratio 0.9990
n=10000: n(n-1)/2 = 49,995,000   n²/2 = 50,000,000   ratio 0.9999

As n grows, the exact count and its leading term n²/2 become practically identical, so the smaller terms really don't matter.

Common complexity classes

Big O Name Example n = 1,000 → operations
O(1) constant array access, hash table lookup 1
O(log n) logarithmic binary search ~10
O(n) linear linear search, find max 1,000
O(n log n) linearithmic merge sort, heap sort ~10,000
O(n²) quadratic bubble sort, all pairs 1,000,000
O(2ⁿ) exponential all subsets, naive Fibonacci ~10³⁰¹
O(n!) factorial all orderings (brute-force TSP) ~10²⁵⁶⁷
python · try it yourself
import math

print(f"{'n':>5} {'log n':>6} {'n log n':>9} {'n²':>9} {'2ⁿ':>22}")
for n in [8, 16, 32, 64]:
    print(f"{n:>5} {math.log2(n):>6.0f} {n * math.log2(n):>9.0f} {n * n:>9} {2 ** n:>22,}")
    n  log n   n log n        n²                     2ⁿ
    8      3        24        64                    256
   16      4        64       256                 65,536
   32      5       160      1024          4,294,967,296
   64      6       384      4096 18,446,744,073,709,551,616

At a billion simple operations per second, n = 64 takes 64 ns for O(n), 4 µs for O(n²), and more than 500 years for O(2ⁿ).

Best, worst and average case

The same algorithm can do very different amounts of work on different inputs of the same size. Linear search finds the first element after 1 comparison but needs n for a missing one. We usually quote the worst case, because it is a guarantee. Sometimes the average case is more useful (quick sort: O(n log n) on average, O(n²) in the worst case).

Notation Meaning
O(f(n)) grows at most like f(n) (upper bound)
Ω(f(n)) grows at least like f(n) (lower bound)
Θ(f(n)) grows exactly like f(n) (both bounds)

In everyday use, people say "O" when they mean the tight bound Θ.

Analysing code by its structure

You often don't need to count exactly; the structure tells you:

Pattern Complexity
A fixed number of steps O(1)
One loop over n items O(n)
Two nested loops over n items O(n²)
A loop that halves (or doubles) a value each time O(log n)
Sequential blocks add them, keep the largest: O(n) + O(n²) = O(n²)
A loop around an O(log n) operation O(n log n)
python · try it yourself
import bisect

def count_common(a, b):            # O(n * m): nested loops
    return sum(1 for x in a for y in b if x == y)

def count_common_sorted(a, b):     # O(m log m + n log m): sort b, binary search each x
    b = sorted(b)
    total = 0
    for x in a:
        i = bisect.bisect_left(b, x)
        if i < len(b) and b[i] == x:
            total += 1
    return total

def count_common_set(a, b):        # O(n + m): hash set
    lookup = set(b)
    return sum(1 for x in a if x in lookup)

a, b = list(range(0, 3000, 3)), list(range(0, 3000, 5))
print(count_common(a, b), count_common_sorted(a, b), count_common_set(a, b))
200 200 200

Three correct solutions, three complexities. With 1000 and 600 items, the nested-loop version performs 600,000 comparisons, while the set version does about 1,600 operations.

Space complexity

The same notation describes memory. Counting sort uses O(k) extra space, merge sort O(n), in-place quick sort O(log n) for its recursion, and bubble sort O(1). Often you can trade one for the other: a hash set uses O(n) memory to make lookups O(1).

Tip: Big O tells you how an algorithm scales, not which is faster for small inputs. Insertion sort (O(n²)) beats merge sort (O(n log n)) on 10 elements, which is why real libraries combine them.

Going further: Asymptotic notation in the Algorithm Theory track defines OO, Ω\Omega and Θ\Theta precisely and shows how to prove bounds with limits and recurrences.

Test yourself

An algorithm performs 3n² + 5n + 20 operations. What is its time complexity?

  1. O(1)
  2. O(n)
  3. O(n²)
  4. O(3n² + 5n)

A loop starts with i = n and does i //= 2 until i reaches 1. How many iterations does it make?

  1. About n
  2. About n/2
  3. About log₂ n
  4. About n²

Which grows fastest as n becomes large?

  1. n log n
  2. n²
  3. 2ⁿ
  4. n³