Module 6 · 18 min read · Free chapter
Asymptotic analysis and recurrences
Asymptotic notation compares how running time grows with input size n, ignoring constants. O gives an upper bound, Ω a lower bound and Θ a tight bound. For T(n) = aT(n/b) + f(n), compare f(n) with n^(log_b a): the larger one decides the answer, and a tie adds a log n factor.
Start from zero: why count steps and not seconds
Suppose your teacher hands you a register with the names of 1,000 students in alphabetical order and asks you to find "Ravi". You could start at the first page and read every name until you reach Ravi. Or you could open the register in the middle, see that the names there start with "M", and throw away the first half at once.
The first way may take up to 1,000 looks. The second way halves the register every time, so it needs only about 10 looks, because . Both ways find Ravi, but one is about a hundred times faster, and the gap grows as the register grows.
This is the whole idea of this chapter. We do not ask "how many seconds does the program take?", because the answer changes with the computer, the language and even the weather in the server room. We ask a sharper question: how does the number of basic steps grow as the input size grows?
Why it matters. A fast computer cannot rescue a badly growing algorithm. If your method needs steps, adding just one more item doubles the work, while a method needing steps barely notices. That is why every GATE paper, every IT officer exam and every coding interview asks you to compare growth rates.
Counting steps: input size, best, worst and average case
To count steps, we first fix what the input size means. For a list it is the number of elements, for a matrix it may be the number of rows, and for a graph it is usually the number of vertices and edges . A basic step is any operation that takes a fixed amount of time, such as a comparison, an assignment or an addition.
Now take linear search: look at each element of an unsorted list of numbers until you find the key. If the key is at the first position, you need 1 comparison, which is the best case. If the key is last or absent, you need comparisons, which is the worst case.
The average case depends on what inputs we expect. If the key is present and equally likely to be at any of the positions, the expected number of comparisons is . So the average case of linear search still grows in proportion to .
Exams and engineers usually quote the worst case, for three reasons. It is a guarantee that holds for every input, it is often easy to calculate, and for many algorithms the worst case happens often, for example when a searched item is missing. The average case needs an assumption about the input, so you must always state that assumption.
Why it matters. A bank's server cannot promise customers "usually fast". It must know the worst it can be, so worst-case analysis is the language of guarantees.
Big-O, Big-Omega and Theta
Exact step counts are messy. One version of an algorithm may take steps and another . For large the term swamps everything else, and the constants 3 and 2 depend on the machine anyway. So we keep only the order of growth, and we need precise symbols to say so.
Big-O (upper bound). if there are constants and such that for every . In words, beyond some point f never rises above a fixed multiple of g. For example, once , so .
Big-Omega (lower bound). if for every . Here for all , so it is .
Theta (tight bound). if both are true, that is for all . So , and this is the most informative statement of the three.
Notice that Big-O is only a ceiling. It is perfectly true that and even , but such statements are loose. When an exam asks for "the time complexity", it almost always wants the tightest bound, which is .
Little-o and little-omega are strict versions. means f grows strictly slower, so as ; for example but is not . Similarly means .
A handy test is the limit rule. Compute L = lim as . If , then ; if L is a finite positive number, then ; if , then .
Why it matters. These symbols let two engineers compare algorithms without arguing about processors. They also let you prove that one method will always beat another for big enough inputs, which is what system design needs.
The growth ladder and how to compare functions
Most algorithms you will meet fall on a short ladder of growth rates. From slowest to fastest growing, the standard order is:
To feel the gap, take . Then is about 20, is about , is , and has about 300,000 digits. A computer doing steps a second finishes the job in a fiftieth of a second, needs about 17 minutes for , and could never finish .
| Growth | Typical example | Name |
|---|---|---|
| 1 | Reading an array element by index | constant |
| Binary search | logarithmic | |
| Linear search, finding the maximum | linear | |
| Merge sort, heap sort | linearithmic | |
| Bubble sort, insertion sort in the worst case | quadratic | |
| Checking every subset of items | exponential | |
| Checking every order of cities | factorial |
Two general rules place almost any function on this ladder. First, every power of grows slower than every positive power of , so . Second, every polynomial grows slower than every exponential with base above 1, so .
Bases of logarithms do not matter inside , or . Since , the two differ by a constant factor of about 3.32. But bases of exponentials do matter: , so is not .
When two functions look hard to compare, take the logarithm of both. Suppose you must compare with . Take of both and you get against . Since , the first grows slower.
Why it matters. GATE often gives four or five strange-looking functions and asks you to arrange them. With these two rules and the trick, each comparison takes one line.
Analysing loops and space
Most code is loops, so most analysis is counting how many times a loop body runs. Four patterns cover nearly every exam question.
Pattern 1: independent nested loops. If an outer loop runs times and an inner loop runs times for each outer pass, the body runs times. Three such loops give .
for i = 1 to n
for j = 1 to n
count = count + 1 // runs n² times
Pattern 2: a dependent inner loop. If the inner loop runs times on the -th outer pass, the total is . That is still , only with a smaller constant. Selection sort and insertion sort in the worst case follow this pattern.
Pattern 3: a multiplying counter. If the counter doubles each time, as in "; while : ", the loop runs about times. Halving gives the same count, and so does multiplying by any fixed number , which gives log_k n.
Pattern 4: a harmonic or mixed loop. Take an outer loop over to with an inner loop that jumps up to . The inner loop runs about times, so the total is . The bracket is the harmonic sum, which is , so the total is .
Sometimes a loop runs until a value crosses in a less obvious way. For example, "; while : " squares the counter each time, so goes 2, 4, 16, 256 and so on. After steps equals , so the loop stops when , that is after about steps.
Space complexity counts extra memory in the same way. A loop with a few variables uses extra space. A recursive function uses stack space for every active call, so recursive binary search, with nested calls, uses space while the iterative version uses . Merge sort on an array needs a temporary array to merge into.
Why it matters. Memory, not time, is often the real limit on phones and small embedded devices. That is why exams ask for both, and why "in-place" sorting methods such as heap sort are valued.
Recurrences: substitution and the recursion tree
A recursive algorithm calls itself on smaller inputs, so its running time is naturally written in terms of itself. Such an equation is a recurrence. For binary search, one comparison cuts the problem in half, so , with .
Method 1: unrolling (iteration). Keep substituting the recurrence into itself until a pattern appears. For binary search, . After steps , and the input reaches 1 when , so .
The same method solves the "decrease by one" recurrences. unrolls to , so it is . unrolls to , which is the recurrence of quicksort in its worst case.
Method 2: the recursion tree. Draw each call as a node and write its own work inside it. For merge sort, : the root does work, its two children do each, the four grandchildren each, and so on. Every level adds up to , and there are levels, so .
The tree also handles uneven splits that formulas cannot. In , every full level still adds to . The shortest path to a leaf has length and the longest , and both are , so .
Method 3: substitution (guess and prove). Guess the answer, then prove it by induction. To show is , assume for all . Then , which is at most whenever .
The famous Tower of Hanoi gives a recurrence of a different kind. To move discs, move the top discs aside, move the largest disc, then move the discs back on top. So with , which unrolls to , an exponential.
Why it matters. Divide and conquer, dynamic programming and recursive data structures all lead to recurrences. If you can solve them, you can analyse nearly every algorithm in the syllabus.
The master theorem
Many divide-and-conquer algorithms split a problem of size into parts, each of size , and spend time dividing and combining. Their recurrence has the form , with and . The master theorem solves such recurrences in one step.
The idea comes straight from the recursion tree. The leaves of the tree number , which equals . So let ; the total work at the leaves is . The theorem simply asks which is bigger, the leaf work or the root work .
- Case 1 (leaves win). If for some , then .
- Case 2 (a tie). If , every level does about the same work, so .
- Case 3 (root wins). If for some , and also for some constant , then .
The extra condition in case 3 is called the regularity condition. It makes sure the work really shrinks as we go down the tree, and it holds for all ordinary polynomial .
| Recurrence | , , | vs | Answer |
|---|---|---|---|
| 2, 2, 1 | equal: case 2 | ||
| 1, 2, 0 | equal: case 2 | ||
| 8, 2, 3 | is smaller: case 1 | ||
| 7, 2, about 2.81 | is smaller: case 1 | ||
| 2, 2, 1 | is bigger: case 3 | ||
| 3, 4, about 0.79 | f is bigger: case 3 |
Where the basic theorem fails. It needs a gap of a polynomial factor between and . In , is bigger than only by a factor, so none of the three cases applies. The recursion tree gives levels of cost , , and so on, which add to .
The theorem also does not fit recurrences such as , where the size decreases by subtraction, or . For the second one, substitute and ; the recurrence becomes , so and .
Why it matters. The master theorem turns a long derivation into a quick comparison, which saves minutes in GATE. Knowing where it fails saves you from the most common wrong answers.
Descriptive lens: how written papers ask this
Written papers for IT officer posts, state Assistant Programmer exams and university-level tests ask about complexity in four ways:
- Define and contrast the notations , , , and , usually with an example of each.
- Analyse a given piece of code or pseudo-code and give its time and space complexity.
- Solve a recurrence by two methods, often the recursion tree and the master theorem, and check that the answers agree.
- Argue a design choice, for example why an sort is preferred to an sort for large data even if the sort has a smaller constant.
Practice questions (our own, not previous-year questions).
- Define Big-O, Big-Omega and Theta notation. Show that by finding suitable constants. (10 marks)
- Arrange in increasing order of growth: , , ,, , and . Justify each step. (10 marks)
- Solve by the recursion tree method and verify the answer with the master theorem. (15 marks)
Answer plan for question 3.
- Draw the root with cost and three children of size , so level has nodes each costing .
- Show that level costs , so the costs grow geometrically towards the leaves.
- Note that the tree has levels, so the last level has leaves.
- Conclude that the leaf level dominates and , which is about .
- Verify with the master theorem: , , , and is polynomially smaller, so case 1 gives the same answer.
- Remark that this is the recurrence of Karatsuba's multiplication, which beats the school method.
Quick revision
- Running time is a count of basic steps as a function of input size , not seconds.
- Worst case is a guarantee for every input; average case needs a stated input model.
- is an upper bound, is a lower bound, and is a tight bound that needs both.
- and are strict: tends to 0 or to infinity.
- The ladder is .
- Log bases do not matter inside , but exponential bases do, since is not .
- Nested loops multiply, loops in sequence add, and a doubling counter gives .
- Binary search is , and merge sort is .
- is , and is .
- For the master theorem, compare with where , and remember that a -factor gap is not covered.