Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 1

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

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.

Python · counting pair comparisons as n grows
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}")
Expected output
n=10   unique=True pair_checks=45
n=100  unique=True pair_checks=4950
n=1000 unique=True pair_checks=499500

Look 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 of g(n) once n is large enough. Saying T(n) = 3n + 10 is O(n) is true; strictly speaking O(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 of g(n) for large n.
  • Big-Theta, written Theta(g(n)): a tight bound when T(n) is both O(g(n)) and Omega(g(n)). Our pairwise check on unique items performs n(n - 1) / 2 steps, so its worst-case cost is Theta(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.

Text · relative step counts across complexity classes (exact values)
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,216

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

Python · O(n) returned list vs O(1) auxiliary accumulators
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))
Expected output
running_totals: [4, 3, 6, -2, 3]
max_running_total: 6

When 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

Practice check · 3 questions

Predict growth and space bounds

Apply step counting and asymptotic rules to these short scenarios.

Q1. A report costs `n * m + n^2` steps, where `n` is the number of rows and `m` is the number of rows that a filter selects from those same rows, so the contract guarantees `m <= n`. Which bound is correct and simplest?
Q2. A function takes a string `text` of length `n` and builds a `dict[str, int]` counting how often each ASCII lowercase letter (`a` to `z`) appears, then returns that dict. What is its auxiliary space bound?
Q3. On `n = 100` items, Algorithm A runs `500 * n` steps and Algorithm B runs `2 * n^2` steps. Which finishes fewer steps at `n = 100`, and which is smaller as `n` keeps growing?
Practice only: not graded, not saved, not evidence.

06. Apply it

Write two small functions in a Python scratch file and instrument both with an explicit steps counter:

  1. sum_all_pairs(nums: list[int]) -> int that sums nums[i] + nums[j] for every 0 <= i < j < len(nums).
  2. has_matching_edge(a: list[int], b: list[int]) -> bool that checks if a contains 0 in one pass, then checks if any pair in b sums to 0.

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:

  1. 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.
  2. State the difference between O(g(n)), Omega(g(n)), and Theta(g(n)), explain why O(n + m^2) cannot be simplified to O(m^2), and say what extra fact would let you simplify a two-variable bound.
  3. Give an example of a function with O(n) total space (counting its output) and O(1) auxiliary space.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check