Sub topic 1
Cost model: counting operations and memory
Every structure in this tutorial is judged by two numbers: how many basic steps an operation takes, and how much memory it needs. This chapter fixes the vocabulary and the counting habits that the later chapters use. GATE questions often ask for an exact count or a tight bound, so you need both skills.
Prerequisites
This chapter assumes you can:
- Read and write loops and functions in C, Java, or Python.
- Follow a recursive function and trace its calls.
- Recognise Big-O notation at an introductory level, such as O(n) and O(n^2).
- Understand that an object reference or pointer is a stored address.
What we count
We do not measure seconds. Seconds depend on the machine, the compiler, and the cache. Instead we pick a basic operation and count how many times it runs as a function of the input size n.
- For searching, the basic operation is usually a comparison.
- For sorting, it is a comparison or a swap.
- For arrays and linked lists, it is often an element read, an element write, or a pointer hop.
Each basic operation is assumed to cost one unit, which is the unit-cost model. Arithmetic on indices, such as 2*i + 1, is also treated as one unit. The model is a simplification, but it ranks algorithms correctly as n grows.
Counting in code
Here is a linear search that counts its own comparisons.
def linear_search(a, key):
comparisons = 0
for x in a:
comparisons += 1
if x == key:
return True, comparisons
return False, comparisons
a = list(range(1, 101))
print(linear_search(a, 1)) # (True, 1)
print(linear_search(a, 100)) # (True, 100)
print(linear_search(a, 0)) # (False, 100)The same function takes 1, 100, or 100 comparisons depending on the input. That is why we always say which case we mean.
Best, worst, and average case
- Best case is the cheapest input of size n. Here it is 1 comparison, with the key at the front.
- Worst case is the most expensive input of size n. Here it is n comparisons, with the key last or missing.
- Average case needs an assumption about the inputs. If the key is present and equally likely to be at any of the n positions, the expected count is (1 + 2 + ... + n) / n = (n + 1) / 2.
Unless a question says otherwise, "time complexity" means the worst case.
Growth rates
Big-O keeps the dominant term and drops constants. A function f(n) is O(g(n)) if f(n) is at most c times g(n) for all n beyond some n0. Related notations are Omega (a lower bound) and Theta (a tight bound, both at once). The table shows how fast the common classes grow at n = 1024.
| Class | Name | Value at n = 1024 | Typical source |
|---|---|---|---|
| O(1) | constant | 1 | array index, stack push |
| O(log n) | logarithmic | 10 | heap sift along one root-to-leaf path |
| O(n) | linear | 1,024 | traversal, linear search |
| O(n log n) | linearithmic | 10,240 | heap sort |
| O(n^2) | quadratic | 1,048,576 | nested loops |
| O(2^n) | exponential | about 1.8 x 10^308 | naive recursion over subsets |
Two counting rules cover most exam questions:
- Sequential blocks add, so the larger one dominates. An O(n) loop followed by an O(n^2) loop is O(n^2).
- Nested loops multiply. The inner loop below runs 0 + 1 + ... + (n - 1) = n(n - 1)/2 times in total, which is Theta(n^2).
def count_pairs(n):
count = 0
for i in range(n):
for j in range(i):
count += 1
return count
print(count_pairs(10)) # 45Amortized cost
Some operations are usually cheap and occasionally expensive. The amortized cost is the total cost of a sequence of operations divided by the number of operations. It is an average over a sequence, and it involves no probability.
A dynamic array (Python list, C++ vector) is the standard case. When it is full, it allocates a block twice as large and copies every element. The code below counts those copies.
def append_copies(n):
capacity, size, copies = 1, 0, 0
for _ in range(n):
if size == capacity:
copies += size
capacity *= 2
size += 1
return copies
for n in (8, 16, 1000):
print(n, append_copies(n))
# 8 7
# 16 15
# 1000 1023The copies happen at sizes 1, 2, 4, 8, and so on. Their sum is a geometric series that stays below 2n. So n appends cost at most n writes plus 2n copies, which is O(n) in total and O(1) amortized per append. One single append can still cost O(n), so the worst case for one append is O(n).
If the array grew by a fixed amount (say 10 slots) instead of doubling, the copies would add up to about n^2 / 20, which is O(n^2). Amortized O(1) depends on geometric growth.
Space cost
Space has two parts:
- Total space counts the input and everything else.
- Auxiliary space counts only the extra memory the algorithm allocates beyond its input.
When a question says "in O(1) extra space", it means auxiliary space. Reversing a singly linked list by redirecting pointers uses a few local variables, so it is O(1) auxiliary space. Copying the list into a new one is O(n).
Two hidden costs matter:
- Recursion uses stack memory. A recursive function that goes n levels deep uses O(n) space for its call frames, even if it allocates nothing itself. A binary-search recursion uses O(log n).
- Structure overhead. An array of n elements stores n values. A singly linked list stores n values and n next pointers. A doubly linked list stores two pointers per node. Later chapters use this when comparing structures.
The diagram below shows the routine for analysing any piece of code.
Common errors
- Reporting the wrong case. Linear search is O(1) in the best case and O(n) in the worst. Name the case you mean.
- Treating O as exact. O(n^2) is an upper bound. A linear algorithm is technically also O(n^2), so use Theta when you need a tight statement.
- Confusing amortized with average. Amortized costs come from a sequence of operations and have no probability involved. Average-case costs come from assumptions about the input distribution.
- Forgetting that log bases differ only by a constant. log2 n and log10 n are the same class, so the base is dropped inside O.
- Ignoring recursion depth in space analysis.
Exercise
A dynamic array starts with capacity 1 and doubles when full. How many element copies happen in total during 1000 appends, and what is the amortized number of copies per append?
Show answer
Resizes occur when the size is 1, 2, 4, ..., 512, so the copies total 1 + 2 + 4 + ... + 512 = 1023. The amortized cost is 1023 / 1000, about 1.02 copies per append, so the amortized cost is O(1).
Exercise
How many times does the statement count += 1 run in for i in range(n): for j in range(i): count += 1, and what is the complexity? What is the auxiliary space?
Show answer
It runs 0 + 1 + ... + (n - 1) = n(n - 1)/2 times, which is Theta(n^2). The auxiliary space is O(1), because only the variables i, j, and count are used.