Sub topic 1
Measuring Cost by Input Size, Not by Seconds
Prerequisites
This chapter assumes you know variables, loops, functions, lists, and basic algebra. Logarithms are helpful but not required.
Measuring Cost by Input Size, Not by Seconds
An algorithm’s running time depends on its input size. Let n represent the number of input items. Instead of measuring seconds on one computer, count how the number of basic operations changes as n grows.
Seconds vary with hardware, programming language, and other running programs. Operation counts describe the algorithm itself.
For example, reading the first list item takes one step whether the list has 10 items or 10 million. Scanning every item takes about n steps.
def first_item(items):
return items[0] # O(1)
def total(items):
result = 0
for item in items: # O(n)
result += item
return resultHow Functions Grow
Growth rate describes how quickly cost increases as n increases.
| Complexity | Cost when `n` doubles | Example |
|---|---|---|
| `O(1)` | stays about the same | first item |
| `O(n)` | about doubles | one loop |
| `O(n²)` | about quadruples | nested loops |
| `O(2ⁿ)` | squares | naive recursive Fibonacci |
A quadratic algorithm can be acceptable for small inputs but expensive for large ones. An exponential algorithm becomes impractical quickly.
What Big O Means
Big O gives an asymptotic upper bound: a limit on how quickly an algorithm’s cost can grow for sufficiently large n.
Formally, f(n) = O(g(n)) if there are constants c > 0 and n₀ such that:
f(n) ≤ c × g(n) for every n ≥ n₀.
The constants allow differences in machine speed and implementation details. Big O focuses on the growth pattern.
Simplifying Cost Expressions
Drop constant factors and lower-order terms. For example:
3n² + 5n + 7 becomes O(n²) because n² eventually dominates the other terms.
Sequential parts add:
O(n) + O(n²) = O(n²).
Nested loops multiply when each loop runs n times:
n × n = n², so the result is O(n²).
Exercise
What is the Big O complexity of a loop that visits every item once and performs a constant amount of work per item?
Show answer
O(n), because the work grows linearly with the number of items.