FOLLOW EACH STEP
Time complexity
Checking ten numbers one by one takes very little work, yet searching through a million numbers is a very different matter. Timing a program with a stopwatch is unreliable, because a faster machine or another implementation alters the measured seconds. What determines whether a method remains practical as data grows is how the count of key operations scales with the input size. The framework for describing and comparing that scaling is time complexity together with Big O notation.
To ground those notations in concrete steps, we return to linear search and binary search from searching algorithms and count operations directly: for a single loop, for a nested loop filling an grid, and from repeated halving, before comparing them with when doubles. Built on those concrete counts, the formal Big O bound uses the same leading-growth comparison developed in limits and relative growth, and allows us to keep best case, worst case, and growth class clearly separated.
After this page, you should be able to solve
- Count the operations in a single loop, two consecutive loops, and two nested loops to obtain , , and , and explain why nesting multiplies the work to while running loops in sequence only adds it and stays .
- Derive logarithmic growth from repeated halving on a sorted array, account for the final comparison omitted by ideal halving, and show why switching to another fixed base changes the count by a constant factor and leaves the Big O class unchanged.
- Simplify a concrete operation count such as or to its Big O bound by selecting an explicit constant multiplier and starting size so that holds for all .
- Predict how the amount of work changes when the input size doubles under , , , , and , while keeping best case, worst case, and Big O as an upper bound on growth clearly distinct.
Begin with a search.
An algorithm is a sequence of instructions for solving a problem. Suppose we have a list of numbers and want to find a particular one. Linear search starts at the first item, compares it with our target, then moves to the next item if they differ.
Let be the number of items: the input size. Here one piece of work is one comparison with an item. Let denote the number of these comparisons. We are counting work, not elapsed seconds.
0
10
Press Play or Step. We are looking for 21; no comparison has happened yet.
Choose the last element. With 5 items, we compare 5 times; with 10 items, 10 times. If there are n items, finding the last one—or confirming that a target is absent—requires n comparisons. This is the worst case: the most work needed among inputs of the same size.
This growth is linear: doubling the list doubles the worst-case comparison count. We describe that bound as , read “big O of n”. The expression inside O tells us a growth scale. It is not the name of a particular algorithm.
What changes when one loop is inside another?
A for loop repeats a block of instructions. Now let the outer loop repeat n times. Inside each repetition, another loop repeats n times. Watch the inner loop finish a whole row before the outer loop moves to the next row.
for i = 0 … n−1: for j = 0 … n−1: mark(i, j)
The outer loop chooses a row. For that row, the inner loop visits every column. One coloured square means one execution of mark(i, j).
No square has been marked yet.
We assumed that marking one square takes a fixed amount of work, independent of n. There are n rows with n squares each. Doubling n doubles both dimensions, so the body runs four times as often. This is quadratic growth. Checks and increments add work, but do not change the quadratic leading growth.
What if the two loops are consecutive, not nested?
The first does n pieces of work, then the second does n more. The total is 2n, not n². Its growth is still linear: . Nesting matters because the whole inner loop repeats for every outer iteration.
Can one comparison remove many possibilities?
It can, if the array is already sorted from small to large and we can access its middle directly. Compare the middle value with the target. If it is too small, every value to its left is also too small. Discard that part. If it is too large, discard the right part. Repeat with the remaining interval. This is binary search.
0
5
Press Play or Step. We are looking for 33; no comparison has happened yet.
To see the growth, first use an ideal halving calculation. After one halving, about candidates remain; after two, about . If is the number of halvings needed to reach one candidate, then:
The logarithm answers a question: “2 raised to which power gives n?” For 8 candidates, gives three ideal halvings, because . Doubling the input adds only one halving. That is much slower growth in work than checking twice as many items.
A halving count is not always the exact comparison count.
The ideal halving calculation described the growth, but it did not count the final comparison. In the actual search, each unsuccessful comparison removes the middle item as well as one side. With m candidates, the larger side has floor(m/2) items; “floor” means round down to an integer. Keeping that larger side repeatedly gives the longest possible route. The step-by-step count below derives the exact bound, including the final candidate, rather than asking us to treat it as another formula to remember.
The sorting must already be done. Sorting an unsorted input costs additional work, which this search count does not include. We use base 2 here because each step roughly halves the candidates. If we instead measured progress in groups of b, the number of such groups would satisfy . Taking base-2 logarithms gives , hence . For a fixed b greater than 1, the divisor is a fixed positive number, so this change of base does not change the growth class.
Count the final comparison too
With eight items, choosing the left of the two middle positions leaves three items on its left and four on its right. Suppose the target exceeds every item: each comparison retains the larger right side, so this really follows a longest route. Predict how many candidates remain after each comparison before advancing.
- Start: 8
One remaining item is not yet an answer: it still needs a comparison to match or reject it. Count until zero. Each step divides the candidate count by two and rounds down; repeating this is the same as rounding down after division by a power of two. Let n be the starting count. Write n₀ for the count before any comparison and nₖ for the count left after k comparisons. The small lower label records how many comparisons have taken place.
The brackets mean round down, and k counts comparisons already made. Zero candidates means that the nonnegative number inside the brackets is below one, or that two to the power k exceeds n. The logarithm answers “how many factors of two reach n?” Taking the smallest integer strictly above that value finishes the worst-case count.
This is both an upper bound on every search and a count attained by the “target exceeds every item” example. It does not include the work of sorting.
But do we always reach the last item?
Of course not. Return to linear search and choose the first item: one comparison finds it, whatever the list length. Its best case is , meaning bounded work independent of n. A middle target and an absent target can require very different amounts of work on equally long lists.
Suppose a family of inputs always makes the search stop 12 items before the end. For , the count is . Those 12 saved comparisons are fixed; when n grows, the term is what grows. We therefore simplify its growth description to . Writing describes the same asymptotic class here (how the work grows once n is large), but hides the simple linear pattern.
Time complexity describes how the work of an algorithm grows with input size. Big O gives an eventual upper bound on that growth, up to a fixed multiplier. It does not by itself mean “worst case”: we chose worst-case work for our search comparisons. We should always say which case and which operation we are counting.
Here is a fixed multiplier and is a fixed starting size; neither changes with n. The function g(n) supplies the growth scale. An upper bound need not be the closest one: linear work is also bounded by a quadratic function eventually, but O(n) describes it more informatively.
Find one bound that keeps working
Suppose each item costs three operations and preparation always costs twelve. The total is . We want a simpler line, , above it. Once chosen, C must stay fixed; we cannot secretly change it for each n.
One numerical comparison checks only one example. To cover every later input, subtract 3n from both sides. This reveals exactly what remains to prove.
With C = 6, every integer n at least 4 works. Increasing n only increases the positive right side, so this proves the entire tail, not just the three examples.
Even if a particular C fails, we have found at least one choice that works: C = 6, starting at n = 4. Big O requires the existence of such a choice, not that every C works. This meets the big-O requirement: choose a fixed multiplier and a starting size, beyond which the operation count never exceeds the bound. Here . Big O supplies an upper bound; it does not claim that each item costs just one operation.
The next comparison also includes exponential growth. Imagine listing every possible yes/no choice for n independent questions. Each new question doubles the number of complete answer lists, giving . This is a count of all combinations, not the cost of answering one list.
The three bars share one linear scale, from 0 to . The scale stretches when changes; the numbers are the actual function values. A short bar has not stopped growing.
| n | ||||
|---|---|---|---|---|
| 4 | 2 | 4 | 16 | 16 |
| 8 | 3 | 8 | 64 | 256 |
| 16 | 4 | 16 | 256 | 65,536 |
| 32 | 5 | 32 | 1024 | 4,294,967,296 |
For a polynomial work count with fixed coefficients, the highest power eventually dominates the lower powers. We can check this without guessing. Suppose the count is . When , and , so:
The multiplier 20 stays fixed, so the count is O(n²). This is the same leading-growth idea explored in Limits: relative growth. Exponential, power, root, and logarithmic expressions grow at different rates. We compare their eventual growth, not just the steepness of a short piece of graph.
Check your understanding: the input doubles.
Linear growth multiplies by 2; quadratic growth multiplies by 4; log₂ n increases by 1. These are growth-function comparisons, not promises that every real computer runs in precisely those time ratios.
