Skip to main content

Complexity Analysis: Counting the Cost of an Algorithm

In the previous lesson we saw that measurements depend on the machine, the compiler and the implementation, and that comparing algorithms only by running them has serious limitations. We now develop the alternative: studying the algorithm on paper, by counting how many elementary operations it performs as a function of the size of its input.

The result is a function, T(n)T(n), that describes the cost of the algorithm independently of any particular computer. It allows us to compare algorithms before implementing them, to predict their behavior for large inputs and to understand why one is better than another.

What you will learn in this lesson
  • The cost model used to analyze algorithms: elementary operations that take one unit of time.
  • How to obtain T(n)T(n) by counting how many times each instruction executes, for loops, conditionals and method calls.
  • The summation formulas that appear most often when analyzing loops.
  • Why the cost of an algorithm can depend on the content of the input, and how we handle it with the best, worst and average cases.
  • How to analyze the memory an algorithm needs, S(n)S(n), including the call stack.

The Cost Model​

To analyze an algorithm mathematically, we use an idealised computer with the following rules:

  • Elementary operations take exactly one unit of time (u.t.): assigning a value, an arithmetic operation, a comparison, a logical operation, accessing an element of an array, returning from a method...
  • Instructions are executed one after another (no parallelism).
  • Memory is unlimited and accessing any position takes the same time.

This model is a deliberate simplification. In a real processor a division is slower than an addition, and accessing data that is in the cache is much faster than accessing main memory. But all these differences are bounded by constants: a division may cost, say, 20 times more than an addition, but never nn times more. Since our goal is to understand how the cost grows with nn, constant factors do not change the conclusions, as the next lesson will make precise.

Not every line of code is elementary

A line such as Arrays.sort(v), list.contains(x) or text.indexOf(word) looks like a single instruction, but it executes a whole algorithm whose cost depends on the size of the data. When analyzing a program, always ask how much a library call really costs. In the exercises of this course, we will make it explicit, for example by writing instruction_O(n) for an operation whose cost grows linearly.

The size of the input​

As we saw in the previous lesson, the cost is expressed as a function of the size of the input, nn: the number of elements of a vector, of a matrix or of the records of a table, the number of nodes of a graph, etc. Sometimes more than one parameter is needed: the cost of an algorithm on a graph usually depends on both the number of nodes and the number of edges, and the cost of processing an r×cr \times c matrix depends on both dimensions.


Counting Operations: The Sum of a Vector​

Let us calculate the exact execution time T(n)T(n) of an algorithm that sums all the integers of an array.

public static int sum(int[] list) {
int value = 0;
for (int i = 0; i < list.length; i++) {
value += list[i];
}
return value;
}
🧠 Checkpoint: Before reading on

Question: Counting each elementary instruction as one unit, which of these expressions is the execution time of this method? (a) 2n2n (b) 3n+43n+4 (c) 3n+33n+3 (d) 2n+32n+3

Answer: (b) 3n+43n+4. Check it with the table below. The most common mistake is to forget that the loop condition is evaluated one extra time, the one that returns false and ends the loop.

Let us count how many times each instruction is executed, with nn = list.length:

LineInstructionExecutionsExplanation
2int value = 0;11Runs once, at the beginning.
3int i = 0;11The initialization of the loop runs once.
3i < list.lengthn+1n + 1Checked before each of the nn iterations, plus one final time that evaluates to false.
3i++nnExecuted at the end of each iteration.
4value += list[i];nnThe body of the loop runs nn times.
6return value;11Runs once, at the end.

Adding up the executions:

T(n)=1+1+(n+1)+n+n+1=3n+4T(n) = 1 + 1 + (n + 1) + n + n + 1 = 3n + 4

For an array of 1,000 elements, this model predicts 3,004 elementary operations.

How precise is "exact"?

Is value += list[i] one operation, or three (read list[i], add, assign)? Is i++ one or two? Different authors count differently, and they would obtain T(n)=5n+4T(n) = 5n + 4 or 6n+46n + 4 instead of 3n+43n + 4. All these answers have something essential in common: they are proportional to nn for large values of nn. The constants depend on arbitrary counting decisions (and, in reality, on the machine), while the growth does not. This is the key motivation for the asymptotic notation of the next lesson.


Counting Loops with Summations​

When loops are nested, or when the number of iterations of the inner loop depends on the outer one, counting line by line becomes cumbersome. Instead, we express the number of executions of the innermost instruction as a summation and simplify it.

Useful formulas​

SummationClosed formTypical origin
∑i=1n1\displaystyle\sum_{i=1}^{n} 1nnA simple loop.
∑i=1ni\displaystyle\sum_{i=1}^{n} in(n+1)2\dfrac{n(n+1)}{2}An inner loop that runs ii times (triangular loops).
∑i=1ni2\displaystyle\sum_{i=1}^{n} i^2n(n+1)(2n+1)6\dfrac{n(n+1)(2n+1)}{6}Three nested loops with dependent limits.
∑i=0k2i\displaystyle\sum_{i=0}^{k} 2^i2k+1−12^{k+1} - 1Quantities that double at each step.
∑i=0kri\displaystyle\sum_{i=0}^{k} r^irk+1−1r−1\dfrac{r^{k+1} - 1}{r - 1} (for r≠1r \ne 1)Geometric growth with ratio rr.

Example 1: a triangular loop​

for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
count++; // how many times?

For each value of ii, the inner loop runs n−1−in - 1 - i times. Therefore:

∑i=0n−1(n−1−i)=(n−1)+(n−2)+⋯+1+0=n(n−1)2\sum_{i=0}^{n-1} (n - 1 - i) = (n-1) + (n-2) + \cdots + 1 + 0 = \frac{n(n-1)}{2}

This is exactly the "half of the pairs" version of the brute-force pairwise product: about n2/2n^2/2 executions, which still grows quadratically.

Example 2: a loop that doubles its counter​

for (int i = 1; i <= n; i *= 2)
count++; // how many times?

The counter takes the values 1,2,4,8,…,2k1, 2, 4, 8, \dots, 2^k, and the loop stops when 2k>n2^k > n. The number of iterations is the number of powers of 2 that do not exceed nn:

⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1

For n=1,000,000n = 1{,}000{,}000 that is only 20 iterations. Loops whose counter is multiplied or divided by a constant run a logarithmic number of times, a pattern that we will meet in binary search and in divide and conquer algorithms.

Example 3: a matrix​

long total = 0;
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
total += matrix[r][c];

The body executes rows⋅colsrows \cdot cols times. If we take nn as the number of elements of the matrix, the algorithm is linear in nn. If the matrix is square and we take nn as its order (number of rows), the same algorithm executes n2n^2 times. Both statements are correct: what changes is the meaning of nn, which is why it must always be stated explicitly.


Conditionals and Method Calls​

  • Sequence. The cost of a sequence of instructions is the sum of their costs.
  • Conditional (if (c) A else B). The cost is the cost of evaluating the condition plus the cost of the branch that is executed. Since we may not know which branch will run, we consider the most expensive one when we want an upper bound, and this naturally leads to distinguishing cases (see below).
  • Loop. The cost is the sum, over all iterations, of the cost of the condition and the body, plus one final evaluation of the condition.
  • Method call. The cost is the cost of the code of the method, applied to the size of its arguments, plus a constant for the call itself. When the method is recursive, this leads to equations in which T(n)T(n) is defined in terms of TT applied to smaller sizes (recurrences), which you will learn to solve in the divide and conquer chapter.

Best, Worst and Average Case​

For the sum of a vector, T(n)T(n) depends only on nn: the loop always performs the same work, whatever the values in the vector. But for many algorithms, two inputs of the same size can require very different amounts of work. Consider searching for a value:

public static boolean contains(int[] list, int value) {
for (int i = 0; i < list.length; i++)
if (list[i] == value)
return true; // found: stop immediately
return false;
}
Best and worst case of sequential search in the same array of 8 elements127315189263search 12best case: 1 comparison127315189263search 185 comparisons127315189263search 40worst case: n = 8 comparisonsblue: compared without success · green: found · gray: never inspected
Three searches in the same array of size 8. The size is the same, but the work goes from 1 comparison (the value is first) to 8 (the value is not there).

If the value is in the first position, the method returns after one iteration. If it is not in the vector, it must inspect all nn elements. To characterise algorithms like this one, we distinguish three cases:

Definition: Tworst(n)T_{worst}(n) is the maximum time of the algorithm over all inputs of size nn. For contains, it corresponds to the value not being present (or being in the last position): all nn elements are inspected.

Value: it is a guarantee: the algorithm will never take longer, whatever the input. This is the case that is analyzed most often, and the essential one in critical systems that must respond within a deadline (aircraft, medical devices, industrial control).

A small average-case calculation​

Suppose that the value we look for is in the vector, and that it is equally likely to be in any position, so each position has probability 1/n1/n. If it is in position ii (counting from 1), contains inspects ii elements. The expected number of inspected elements is:

∑i=1n1n⋅i=1n⋅n(n+1)2=n+12\sum_{i=1}^{n} \frac{1}{n} \cdot i = \frac{1}{n} \cdot \frac{n(n+1)}{2} = \frac{n+1}{2}

On average, we inspect about half of the vector: still proportional to nn. In the lesson on searching we will repeat this analysis counting every instruction, and also considering the possibility that the value is not present.

🧠 Checkpoint: Which case?

Question: For the maximum pairwise product algorithms of the case study (brute force, sorting, linear scan), do the best, worst and average cases differ?

Answer: For brute force and for the linear scan, essentially no: both always traverse the same loops completely, whatever the values (only the number of times the if body executes changes, which does not affect the growth). For the version based on sorting, it depends on the sorting algorithm: some sorting algorithms (such as the TimSort used by Java for objects) are much faster when the data is already sorted. Analyzing the cases always requires looking at which inputs make the algorithm work more or less.

Amortised cost

There is a fourth way of looking at cost, which we mentioned when studying ArrayList: the amortised cost, which is the average cost per operation over a sequence of operations, in the worst case. An ArrayList occasionally performs an expensive copy when it grows, but over any long sequence of insertions the average cost per insertion is constant.


Space Complexity: S(n)S(n)​

Time is not the only resource. The space complexity S(n)S(n) measures the additional memory that an algorithm needs, as a function of the size of the input, beyond the memory occupied by the input itself. It is analyzed with the same counting approach: how many variables, and of what size, does the algorithm create?

  • The sum of a vector needs two variables (value and i), whatever the value of nn: its additional space is constant.
  • An algorithm that copies the input into a new array, or that creates an auxiliary array of the same size (as Mergesort does), needs space proportional to nn.
In-place and out-of-place algorithms
  • An algorithm is in place when it transforms the input using only a constant (or very small) amount of additional memory, such as a few variables.
  • An algorithm is out of place when it needs additional memory that grows with the input, such as auxiliary arrays or copies.

Do not forget the stack​

Recursive algorithms consume memory even if they do not create any data structure: each active call occupies a frame on the call stack. The recursive factorial of the first lesson performs nn nested calls before reaching the base case, so it needs stack space proportional to nn; the iterative version needs constant space. This is why a deep recursion can end with a StackOverflowError even when the algorithm is correct.

The time-memory trade-off​

Time and space are often exchanged: we can sometimes save a lot of time by storing results that would otherwise have to be recomputed (the main idea of dynamic programming), or save memory at the cost of recomputing. An engineer must consider both resources and choose the balance that fits the constraints of the problem.

Common mistakes
  • Counting a library call as one operation. Arrays.sort, contains or indexOf hide loops; count their real cost.
  • Taking the best case as "small nn". The best case is the most favourable input of size nn, not n=1n = 1.
  • Taking the average case as the mean of the best and worst cases. It needs assumptions about the probability of each input.
  • Forgetting the call stack in S(n)S(n). A recursion of depth nn uses O(n)O(n) memory even if it creates no arrays.

Summary​

  • We analyze algorithms in an idealised model in which each elementary operation costs one unit of time. Library calls are not necessarily elementary.
  • T(n)T(n) is obtained by counting how many times each instruction executes. For the sum of a vector, T(n)=3n+4T(n) = 3n + 4.
  • Nested and dependent loops are counted with summations; loops whose counter is multiplied or divided by a constant run a logarithmic number of times.
  • The exact constants depend on counting conventions, but the growth does not.
  • When the cost depends on the content of the input, we distinguish the best, worst and average cases. The worst case is a guarantee; the average case requires assumptions about probabilities.
  • S(n)S(n) measures the additional memory, including the call stack used by recursion.

Practice​

  • 🧮 Count it. Obtain T(n)T(n), counting each instruction as one unit, for a method that returns the maximum of a non-empty vector of nn integers. Does the result depend on the content of the vector? (Hint: the assignment inside the if may or may not execute.)
  • 📐 Use summations. How many times does the innermost instruction run in this fragment? for (i = 0; i < n; i++) for (j = 0; j < i; j++) for (k = 0; k < j; k++) x++; Give the exact formula and its leading term.
  • 🔢 Logarithmic loops. How many iterations does for (i = n; i >= 1; i /= 3) perform? Check your formula for n=1n = 1, n=9n = 9 and n=10n = 10.
  • ⚖️ Cases. For a method that checks whether a vector is sorted in ascending order (returning false as soon as it finds two consecutive elements out of order), describe the best and worst cases and their cost.
  • 💾 Space. Compare the additional space needed by the three versions of the maximum pairwise product (brute force, sorting a copy, linear scan).
  • 💻 Verify experimentally. Add a counter to the sum of a vector that increments once per elementary operation, run it for several values of nn and check that the result is 3n+43n + 4.
Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.