Start from foundations · Course contents · فارسی
Previous lesson: From problem to algorithm: data, tracing and a first cost analysis · Next lesson: Recursion from scratch: from function calls to cost recurrences
Cost analysis from scratch: counting work and time growth
In the previous lesson, one pass found the maximum of a list. What happens to its work if the list becomes a thousand times longer? Stopwatch measurements are useful, but hardware, language and data affect them. We first count operations in an explicit model to understand growth, then supplement that analysis with measurements.
Objective: count a loop's main operations, distinguish addition from multiplication of counts, and explain an upper bound versus a tight growth bound. Only basic multiplication and the previous tracing lesson are required. Necessary formulas and logarithms are introduced here. This is part of the cost-analysis chapter; recurrences and amortized analysis remain future topics.
1. Decide what you are counting
n is the number of input elements, not an element's value. For [1000, 3, 8], n=3. In this lesson we treat reading an element, comparing ordinary machine-sized numbers, and adding two numbers that fit a machine word as constant-cost operations. Adding million-digit integers need not take constant time. The Open Data Structures computation model gives a more precise account of these assumptions.
“Three comparisons” below means three comparisons of data values. It excludes loop-condition tests, counter increments and memory reads. Those contribute to total running time too. A selected operation count is not an exact running time; when representative of the work, it helps us understand time growth.
best = A[0]
for i = 1 to n-1 inclusive:
if A[i] > best:
best = A[i]
Assume n>=1. “Inclusive” means the endpoint is executed. For n=4, i takes values 1, 2 and 3: three data comparisons. In general there are exactly n-1. At n=1 there are zero comparisons, but initialization and returning the answer still require work. An empty array requires a separate contract.
2. Add or multiply? Follow the body executions
Consider two consecutive loops. Each visit is a constant-cost action:
for i = 1 to n inclusive:
visit(i)
for j = 1 to n inclusive:
visit(j)
The first loop makes n calls and the second makes another n: 2n in total. The second loop does not repeat for every iteration of the first, so we do not multiply.
Now put the second loop inside the first:
for i = 1 to n inclusive:
for j = 1 to n inclusive:
visit(i, j)
At i=1, j runs from 1 through n. At i=2, j starts at 1 again. There are n groups, each containing n actions: n*n=n². For n=3, the pairs are (1,1) through (1,3), then (2,1) through (2,3), then three pairs in the third row: nine actions.
The diagram counts only visit calls for n=3. Colors group iterations; they have no effect on running time.
Nested loops do not always perform n² actions. If the inner loop runs from 1 to i, its counts are 1+2+...+n. For n=4, the four rows contain 1, 2, 3 and 4 actions: ten, not sixteen. Write this sum once forward and once backward. Corresponding terms add to n+1, with n such pairs. Twice the sum is n(n+1), so the sum is n(n+1)/2.
3. From exact counts to growth classes
Programs with costs 3n+5 and 10n+2 both grow linearly. That does not imply equal measured times or that constants never matter in practice. Asymptotic analysis describes sufficiently large inputs while abstracting away constant factors and lower-order terms.
Keep three symbols distinct. Here T(n) is a cost function and g(n) is a comparison function:
- O(g(n)), an upper bound: beyond some input size,
T(n)is at most a fixed positive multiple ofg(n). - Ω(g(n)), a lower bound: beyond some input size,
T(n)is at least a fixed positive multiple ofg(n). - Θ(g(n)), a two-sided bound: both conditions hold. Growth is bounded above and below by constant multiples of
g(n).
For T(n)=3n+5 and n>=1, we have 3n<=T(n)<=8n, proving Θ(n). This shows why 3 and 5 do not change the growth class. This function is also O(n²), since 8n<=8n² for n>=1, but it is not Θ(n²). When a question asks for a tight bound, a valid loose upper bound is insufficient. See the asymptotic notation section for definitions.
The triangular sum above is Θ(n²): for n>=1, it lies between n²/2 and n². It does not equal n² exactly. An exact count and a growth class answer different questions.
4. Why logarithms sometimes appear
k = n
while k > 1:
k = floor(k / 2)
floor rounds down to an integer: half of 5 becomes 2. For n=16, the sequence 16 → 8 → 4 → 2 → 1 requires four iterations. Each step halves the size instead of subtracting one. log₂(n) asks which power of 2 equals n. Since 2⁴=16, log₂(16)=4.
For positive integer n, this particular loop has floor(log₂(n)) iterations. For 5, the sequence 5 → 2 → 1 has two. Total running time for n>=2 is Θ(log n). Different fixed bases greater than 1 change only a constant factor. Putting this loop inside an n-iteration loop gives roughly n log n work if k is reset to n on every outer iteration. Without resetting, trace k instead of blindly multiplying.
| Growth | n=8 | n=16 | Effect of doubling input size |
|---|---|---|---|
| n | 8 | 16 | Doubles |
| n² | 64 | 256 | Quadruples |
| log₂(n) | 3 | 4 | Adds one |
5. Best and worst cases are different from O and Ω
Linear search examines elements in order and stops when it finds the target. Among inputs of length n, a target at the first position takes one comparison; an absent target takes n. The best-case cost is therefore Θ(1) and the worst-case cost is Θ(n). Average-case analysis requires a probability distribution over inputs and target positions. “Average is half the worst” is not a general rule.
O is a bound, not another name for worst case. A worst-case cost function can itself receive an upper or lower bound. First identify the function being analyzed, then choose notation.
6. Independent practice and exam tips
These are original practice questions, not quotations from official exams. Write a count or justification before opening an answer.
1. Two consecutive loops make n and n² calls respectively. What are the total count and tight growth bound?
Answer 1
The total is n+n². For n≥1 it lies between n² and 2n², so it is Θ(n²). Consecutive loop counts add rather than multiply.
2. An outer loop runs four times; its inner loop runs n times with a constant-cost body. Does nesting imply quadratic growth?
Answer 2
No. The body executes 4n times, giving Θ(n). Four is a constant independent of input size. Count actual executions before assigning a class.
3. Trace k in the halving loop for n=20 and count iterations.
Answer 3
20 → 10 → 5 → 2 → 1: four body executions. The condition fails at 1. There are five condition checks but four body executions.
4. Original multiple choice: Which claim about 7n+4 is false? A) O(n); B) Ω(n); C) Θ(n²); D) O(n²).
Test answer
C is false. The cost is linear; its ratio to n² tends to zero as n grows, so no fixed positive multiple of n² is an eventual lower bound. D is a correct but loose upper bound.
5. Transfer: Two lists have independent lengths n and m. For each element of the first, inspect every element of the second. How many inspections occur?
Answer 5
Exactly nm inspections. With a constant-cost body and n,m≥1, the time is Θ(nm). Only an additional relation such as m=n allows us to replace it with Θ(n²).
7. Retrieve and continue
Without looking, explain consecutive versus nested loops using a fresh example, then explain why O(n²) can hold for a linear function. If counting fails, write iteration rows for n=3. If notation fails, reconstruct both inequalities for 3n+5. Being able to provide both the count and the reason for the bound is a practical signal to continue, not proof of permanent mastery. Try new values again after a gap.
References and authorship
Explanations, pseudocode, diagrams and exercises were authored for this lesson. Sources checked on 2026-11-23 for the model and notation definitions: Pat Morin, Open Data Structures: computation model and mathematical background. No exam-frequency analysis is claimed.
Previous: from problem to algorithm · Course contents · Start from foundations
Previous lesson: From problem to algorithm: data, tracing and a first cost analysis · Next lesson: Recursion from scratch: from function calls to cost recurrences