Counting Steps Instead of Seconds
Replace machine-dependent wall-clock timing with input-relative step counting, distinguish Big-O, Big-Theta and Big-Omega, and separate auxiliary space from total space.
Contentsand lesson path
On this page
- Why it matters
- From wall-clock seconds to primitive steps
- Big-O, Big-Theta and Big-Omega
- Total space vs auxiliary space—and when Big-O is not enough
- Check your understanding
- Apply it
- Review prompt
Lessons of Complexity Analysis
- Counting Steps Instead of Seconds Concept · 20 min
- Reading Loops: From Code to a Bound Worked example · 25 min
- Worst Case, Average Case and Amortized Cost Concept · 20 min
- Budgeting Operations from Input Limits Worked example · 15 min
- Lab: Timing Growth Curves with timeit Lab · 30 min
- Check: Predict, Then Measure Knowledge check · 8 questions
What you will learn
- Derive Big-O time and space bounds for code with sequential, nested and multi-input loops, dropping constants and lower-order terms correctly.
Prerequisites: Python Foundations
01. Why it matters
Your duplicate-checking script finishes in a few milliseconds on a sample of 100 user IDs during local testing. A month later, someone feeds it 100,000 IDs from production and the job sits frozen for minutes. Nothing in your Python syntax changed, and the laptop CPU is still running at the same clock speed. Why did multiplying the input by 1,000 slow the program down by roughly 1,000,000?
Measuring seconds on one machine cannot answer how code behaves when input grows, because a faster processor or an idle background OS shifts every number by a constant multiplier. Instead, you need a way to count how the number of operations scales with the input size n. In this lesson you build that mental model, starting from what your code does on a single computer and ending with standard asymptotic bounds for both time and memory.
02. From wall-clock seconds to primitive steps
Suppose you check whether a sequence contains any repeated value by comparing every pair of positions. If you run the function on a 10-element test list, you might time it in microseconds and conclude it is fast enough. At small n, that initial approach is completely reasonable: it requires no extra memory, needs no hashable items, and finishes instantly.
The problem is that the number of comparisons grows much faster than the list itself. To reason independently of hardware, computer science uses a simplified model (the Random Access Machine, or RAM model): each basic arithmetic operation, assignment, comparison, or array index read counts as one constant-time step. This is a deliberate simplification: in real hardware, a CPU cache miss or a Python heap allocation takes far longer than adding two integers, and Python integer arithmetic itself grows slower if numbers exceed machine word size. Even with those details stripped away, step counting captures the shape of growth accurately enough to predict when a solution will blow past its latency budget.
from collections.abc import Sequence
def count_steps_distinct(items: Sequence[int]) -> tuple[bool, int]:
"""Return (all_unique, comparison_steps) using pairwise checks."""
steps = 0
for i in range(len(items)):
for j in range(i + 1, len(items)):
steps += 1
if items[i] == items[j]:
return False, steps
return True, steps
for size in (10, 100, 1_000):
ok, ops = count_steps_distinct(list(range(size)))
print(f"n={size:<4} unique={ok} pair_checks={ops}")n=10 unique=True pair_checks=45
n=100 unique=True pair_checks=4950
n=1000 unique=True pair_checks=499500Look at the jump from n = 100 to n = 1,000: multiplying n by 10 multiplied pair_checks by roughly 100 (from 4,950 to 499,500). Notice why: for n unique elements, the inner loop checks n - 1 items, then n - 2, down to 1, which totals n(n - 1) / 2 = (1/2)n^2 - (1/2)n. If you switch to a faster CPU that executes twice as many steps per second, you halve the runtime, but multiplying n by 10 still multiplies the runtime by 100. What if you changed the code to compare each item with a neighbour only (items[i] == items[i + 1] on sorted data)? Then steps would be n - 1, so multiplying n by 10 would multiply work by 10 rather than 100.
03. Big-O, Big-Theta and Big-Omega
Once you express cost as a function T(n) such as 0.5n^2 - 0.5n + 3, keeping every coefficient clutters the comparison without helping you predict scaling at large n. Asymptotic notation drops positive constant multipliers and lower-order terms so you can classify the growth rate:
- Big-O, written
O(g(n)): an asymptotic upper bound.T(n)grows no faster than a constant multiple ofg(n)oncenis large enough. SayingT(n) = 3n + 10isO(n)is true; strictly speakingO(n^2)is also a valid upper bound, though engineers normally give the tightest simple upper bound. - Big-Omega, written
Omega(g(n)): an asymptotic lower bound.T(n)grows at least as fast as a constant multiple ofg(n)for largen. - Big-Theta, written
Theta(g(n)): a tight bound whenT(n)is bothO(g(n))andOmega(g(n)). Our pairwise check on unique items performsn(n - 1) / 2steps, so its worst-case cost isTheta(n^2).
From slowest-growing to fastest-growing, the classes you will meet most often are O(1) (constant), O(log n) (logarithmic), O(n) (linear), O(n log n) (linearithmic), O(n^2) (quadratic), and O(2^n) (exponential). Whenever a sum mixes classes in the same variable n—such as n^2 + 50n + 200—only the dominant term n^2 survives as n grows. By contrast, if a function reads two separate inputs of lengths n and m, neither variable can absorb the other: scanning n items then m^2 pairs is O(n + m^2) because n might be 10^7 while m is 5.
The exception is a stated relation between the inputs. Suppose the data contract promises m <= n, for example because m counts the rows that a filter selects from the same n rows. Then n * m can never exceed n * n, so a cost of n * m + n^2 is at most 2n^2 and simplifies to O(n^2). Use a relation only when the specification guarantees it; a relation that merely holds in today's test data is not a bound.
n O(log2 n) O(n) O(n log2 n) O(n^2)
----------------------------------------------------------
16 4 16 64 256
256 8 256 2,048 65,536
4,096 12 4,096 49,152 16,777,21604. Total space vs auxiliary space—and when Big-O is not enough
Memory grows with n just like steps do, and analysts track two counts. In this skill, total space counts everything a function allocates, including the output it builds and returns; the input does not count, because the caller already owns it. Auxiliary space (also called extra space) is narrower: only the temporary working memory, excluding both the input and the returned output. Some textbooks also add the input to total space, so state your convention whenever the difference matters.
Consider computing running prefix sums of a list of n integers. running_totals below returns a new list of n integers, so its total space is O(n), while its auxiliary space is O(1): apart from the output it keeps only the accumulator acc. If you only need the maximum running sum, max_running_total keeps two scalars (best and acc) and returns one integer, so both its total and its auxiliary space are O(1) however long nums becomes.
def running_totals(nums: list[int]) -> list[int]:
"""Return all prefix sums (O(n) space for the returned list)."""
out: list[int] = []
acc = 0
for x in nums:
acc += x
out.append(acc)
return out
def max_running_total(nums: list[int]) -> int:
"""Return the largest prefix sum using O(1) auxiliary space."""
best = 0
acc = 0
for x in nums:
acc += x
if acc > best:
best = acc
return best
sample = [4, -1, 3, -8, 5]
print("running_totals:", running_totals(sample))
print("max_running_total:", max_running_total(sample))running_totals: [4, 3, 6, -2, 3]
max_running_total: 6When not to rely on Big-O alone: asymptotic bounds ignore constant factors and cache behaviour, so they lose predictive power when n is small or when two algorithms differ by a large constant factor. An O(n) algorithm that parses JSON or hits disk on every item can easily be slower than an O(n^2) loop over ten integers in CPU registers. Likewise, in Python, operations implemented in C (such as sum() or sorted()) carry much smaller constants per element than an explicit Python for loop. Use Big-O to choose the right scaling family and eliminate infeasible growth rates, then measure real inputs when constants matter—just as we saw earlier in Choosing Lists, Dicts, Sets, Tuples and Dataclasses and will quantify across Arrays & Strings and Hashing & Hash Tables.
05. Check your understanding
06. Apply it
Write two small functions in a Python scratch file and instrument both with an explicit steps counter:
sum_all_pairs(nums: list[int]) -> intthat sumsnums[i] + nums[j]for every0 <= i < j < len(nums).has_matching_edge(a: list[int], b: list[int]) -> boolthat checks ifacontains0in one pass, then checks if any pair inbsums to0.
Run both at n = 5, 50, 500 (and len(a) = 1000, len(b) = 10 vs len(a) = 10, len(b) = 100) and record the exact steps counts. State both the time bound and the auxiliary space bound of each function before moving on to the worked examples in Reading Loops: From Code to a Bound.
07. Review prompt
Without looking back at the tables or code:
- Explain in your own words why the RAM model counts primitive operations rather than milliseconds, and name one real hardware detail that this model omits.
- State the difference between
O(g(n)),Omega(g(n)), andTheta(g(n)), explain whyO(n + m^2)cannot be simplified toO(m^2), and say what extra fact would let you simplify a two-variable bound. - Give an example of a function with
O(n)total space (counting its output) andO(1)auxiliary space.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.