Solve (a) T(n) = 2T(n/2) + n, (b) T(n) = 4T(n/2) + n, (c) T(n) = 2T(n/2) + n², (d) T(n) = T(2n/3) + 1.
Algorithm analysis predicts how running time and memory grow with the input size n. Asymptotic notation — O (upper bound), Ω (lower bound), Θ (tight bound) — compares algorithms independently of hardware and is the language of every sorting, tree and graph question.
i++ → n; i *= 2 → log n; two nested → n²; inner j <= i → n(n+1)/2; halving nest n + n/2 + … → Θ(n).An algorithm is a finite sequence of unambiguous steps that turns an input into an output. Two correct algorithms for the same problem can differ enormously in how long they run and how much memory they use, so we analyse them before choosing: we predict their resource use as a function of the input size n — the number of elements to sort, the number of nodes in a tree, or the numbers of vertices and edges in a graph.
Timing a program with a stopwatch is unreliable because the result depends on the processor, the compiler, the language and whatever else the machine is doing. Instead we count basic operations — the step that dominates the work, such as a key comparison in sorting or an edge relaxation in a shortest-path algorithm. We assume the RAM model: every simple operation (assignment, arithmetic, comparison, array access) costs one unit of time.
| Statement | Times executed | Why |
|---|---|---|
sum = 0; | 1 | runs once |
for (i = 0; i < n; i++) | n + 1 | the test i < n is true n times and false once |
sum = sum + a[i]; | n | once per iteration |
return sum; | 1 | runs once |
| Total | 2n + 3 | the order of growth is Θ(n) |
For large n only the order of growth matters. Suppose algorithm P needs 2n + 3 steps and algorithm Q needs 0.5n² steps. Q is faster for n ≤ 5, but at n = 10,000 P needs 20,003 steps while Q needs 50,000,000. Asymptotic analysis formalises this: keep the fastest-growing term and drop its constant coefficient, because no constant can rescue a slower growth rate.
Asymptotic notations describe how a function f(n) behaves for large n by comparing it with a simple reference function g(n) such as n, n² or log n. Each definition uses two witnesses: a positive constant c (which absorbs machine speed) and a threshold n₀ (beyond which the bound must hold; small inputs are ignored).
| Notation | Acts like | Meaning | Example |
|---|---|---|---|
| O | ≤ | f grows no faster than g | 5n + 3 = O(n), and also O(n²) |
| Ω | ≥ | f grows at least as fast as g | n² = Ω(n) |
| Θ | = | f and g grow at the same rate | 3n² + 5n + 2 = Θ(n²) |
| o | < | f grows strictly slower | n = o(n²), but n ≠ o(n) |
| ω | > | f grows strictly faster | n² = ω(n) |
A worked proof. Show 3n² + 5n + 2 = Θ(n²). Lower bound: 3n² ≤ 3n² + 5n + 2 for every n ≥ 1, so c₁ = 3 works. Upper bound: for n ≥ 1 we have 5n ≤ 5n² and 2 ≤ 2n², so 3n² + 5n + 2 ≤ 10n²; take c₂ = 10 and n₀ = 1. A tighter c₂ = 4 also works, but only from n₀ = 6 (at n = 5 the left side is 102 and 4n² is 100) — the constants are not unique, only their existence matters.
Limit test. When the limit L = lim (n→∞) f(n)/g(n) exists: L = 0 means f = o(g) (hence also O(g)); a finite L > 0 means f = Θ(g); L = ∞ means f = ω(g) (hence also Ω(g)). Example: (n log n)/n² = (log n)/n → 0, so n log n = o(n²).
Functions can be arranged by how fast they grow. Each class eventually dwarfs every class to its left, whatever constants are attached:
| Class | Name | Typical algorithms / operations | Steps at n = 1,024 |
|---|---|---|---|
| O(1) | constant | array indexing, stack push/pop, average hash lookup | 1 |
| O(log n) | logarithmic | binary search, heap insert, balanced-BST search | 10 |
| O(√n) | square root | jump search, trial-division primality test | 32 |
| O(n) | linear | linear search, finding the maximum, tree traversal | 1,024 |
| O(n log n) | linearithmic | merge sort, heap sort, average quick sort | 10,240 |
| O(n²) | quadratic | bubble, selection, insertion sort; checking all pairs | ≈ 1.05 × 10⁶ |
| O(n³) | cubic | Floyd–Warshall, naive matrix multiplication | ≈ 1.07 × 10⁹ |
| O(2ⁿ) | exponential | all subsets, Towers of Hanoi, naive recursive Fibonacci (≈ 1.618ⁿ) | ≈ 1.8 × 10³⁰⁸ |
| O(n!) | factorial | all permutations, brute-force travelling salesman | ≈ 5.4 × 10²⁶³⁹ |
Most complexity MCQs show a code fragment. Find the statement that executes most often and count its executions: consecutive blocks add (keep the largest), nested blocks multiply, and an if–else is charged the costlier branch in the worst case. The program below counts the innermost operation for the common loop shapes so you can check each formula.
#include <stdio.h>
long linear(int n) { long c = 0; for (int i = 0; i < n; i++) c++; return c; }
long quadratic(int n) { long c = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) c++; return c; }
long triangular(int n) { long c = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= i; j++) c++; return c; }
long doubling(int n) { long c = 0; for (int i = 1; i < n; i *= 2) c++; return c; }
long halvingNest(int n){ long c = 0; for (int i = n; i > 0; i /= 2) for (int j = 0; j < i; j++) c++; return c; }
long nLogN(int n) { long c = 0; for (int i = 0; i < n; i++) for (int j = 1; j < n; j *= 2) c++; return c; }
long squareRoot(int n) { long c = 0; for (int i = 1; i * i <= n; i++) c++; return c; }
int main(void) {
int n = 16;
printf("linear=%ld quadratic=%ld triangular=%ld\n", linear(n), quadratic(n), triangular(n));
printf("doubling=%ld halvingNest=%ld nLogN=%ld sqrt=%ld\n",
doubling(n), halvingNest(n), nLogN(n), squareRoot(n));
return 0;
}
/* Output:
linear=16 quadratic=256 triangular=136
doubling=4 halvingNest=31 nLogN=64 sqrt=4 */| Loop pattern | Count of innermost statement | Order |
|---|---|---|
for (i = 0; i < n; i++) | n | Θ(n) |
for (i = 0; i < n; i += 2) | ⌈n/2⌉ | Θ(n) |
for (i = 1; i < n; i *= 2) | ⌈log₂ n⌉ | Θ(log n) |
for (i = n; i > 1; i /= 2) | ⌊log₂ n⌋ | Θ(log n) |
for (i = 2; i < n; i = i * i) | about log₂ log₂ n | Θ(log log n) |
for (i = 1; i * i <= n; i++) | ⌊√n⌋ | Θ(√n) |
| two nested loops, each 0 … n−1 | n² | Θ(n²) |
for (i = 1..n) for (j = 1..i) | n(n + 1)/2 | Θ(n²) |
outer 0 … n−1, inner j *= 2 up to n | n⌈log₂ n⌉ | Θ(n log n) |
outer i /= 2 from n, inner j < i | n + n/2 + n/4 + … < 2n | Θ(n) |
outer i = 1..n, inner j += i up to n | ≈ n(1 + ½ + … + 1/n) ≈ n ln n | Θ(n log n) |
For a recursive function, write a recurrence — an equation that gives T(n) in terms of T on smaller inputs plus the non-recursive work — and solve it with the methods in the recurrence section below.
For a fixed n, different inputs can cost different amounts. The worst case is the maximum cost over all inputs of size n — a guarantee, and the figure quoted by default. The best case is the minimum. The average case is the expected cost under an assumed input distribution, usually ‘all inputs equally likely’.
| Algorithm | Best case | Average case | Worst case |
|---|---|---|---|
| Linear search | 1 comparison — key in first position | (n + 1)/2 comparisons, Θ(n) | n comparisons — key last or absent |
| Binary search | 1 comparison — key at the middle | ≈ log₂ n − 1, Θ(log n) | ⌊log₂ n⌋ + 1 comparisons |
| Insertion sort | Θ(n) — already sorted (n − 1 comparisons) | Θ(n²) | Θ(n²) — reverse sorted, n(n − 1)/2 comparisons |
| Quick sort | Θ(n log n) — balanced splits | Θ(n log n) | Θ(n²) — sorted input with first/last-element pivot |
| Merge sort | Θ(n log n) | Θ(n log n) | Θ(n log n) |
| BST search | Θ(1) — key at the root | Θ(log n) — randomly built tree | Θ(n) — skewed tree |
Space complexity is the memory an algorithm needs as a function of n. Horowitz and Sahni split it as S(P) = c + S_P(n): a fixed part c (instructions, simple variables, constants) plus a variable part S_P that depends on the instance (dynamically allocated arrays and the recursion stack). Auxiliary space counts only the extra memory beyond the input itself; an algorithm with O(1) auxiliary space works in place.
| Algorithm | Auxiliary space | Reason |
|---|---|---|
| Iterative binary search | O(1) | three index variables |
| Recursive binary search | O(log n) | one stack frame per halving |
| Recursive factorial / linear recursion | O(n) | n pending calls on the stack |
| Merge sort (arrays) | O(n) | temporary array for merging |
| Quick sort | O(log n) average, O(n) worst | recursion depth |
| Heap sort | O(1) | sorts inside the array |
| BFS / DFS | O(V) | queue or stack plus the visited array |
A recursive algorithm's cost is described by a recurrence. There are three standard ways to solve one: the substitution or iteration method (unroll it until a pattern appears, or guess the answer and prove it by induction), the recursion-tree method (draw the calls and add the work level by level), and the Master theorem, a ready-made answer for divide-and-conquer recurrences.
The recursion tree tells the same story visually: level 0 has one problem of size n doing n work, level 1 has two problems of size n/2 doing n/2 each, level 2 has four of size n/4, and so on. Every level totals n, there are log₂ n + 1 levels, so the total is about n log₂ n.
Intuition: n^(log_b a) is the total work done at the leaves of the recursion tree and f(n) is the work at the root. If the leaves are polynomially heavier, they dominate (case 1); if the root is polynomially heavier and the work shrinks going down (the regularity condition), the root dominates (case 3); if they balance, every level costs about the same and we multiply by the log n levels (case 2).
| Recurrence | Solution | Where it arises |
|---|---|---|
| T(n) = T(n/2) + 1 | Θ(log n) | binary search (Master case 2) |
| T(n) = T(n/2) + n | Θ(n) | halving with linear work, e.g. quickselect best case (case 3) |
| T(n) = 2T(n/2) + 1 | Θ(n) | tree traversal, recursive maximum of an array (case 1) |
| T(n) = 2T(n/2) + n | Θ(n log n) | merge sort, best-case quick sort (case 2) |
| T(n) = 2T(n/2) + n² | Θ(n²) | root-dominated (case 3) |
| T(n) = 3T(n/2) + n | Θ(n^log₂3) ≈ Θ(n^1.585) | Karatsuba multiplication (case 1) |
| T(n) = 7T(n/2) + n² | Θ(n^log₂7) ≈ Θ(n^2.81) | Strassen's matrix multiplication (case 1) |
| T(n) = 8T(n/2) + n² | Θ(n³) | naive divide-and-conquer matrix multiplication (case 1) |
| T(n) = T(n − 1) + 1 | Θ(n) | recursive factorial, recursive linear search |
| T(n) = T(n − 1) + n | Θ(n²) | worst-case quick sort, selection sort |
| T(n) = 2T(n − 1) + 1, T(1) = 1 | 2ⁿ − 1 = Θ(2ⁿ) | Towers of Hanoi |
| T(n) = T(n − 1) + T(n − 2) + 1 | Θ(φⁿ), φ ≈ 1.618 | naive recursive Fibonacci |
Some operations are usually cheap but occasionally expensive. Amortised analysis bounds the total cost of the worst possible sequence of m operations and divides by m. Unlike average-case analysis it uses no probability: the amortised bound is guaranteed for every sequence, it simply spreads the rare expensive step over the many cheap ones.
| Method | Idea | Dynamic-array example |
|---|---|---|
| Aggregate | Find the total cost T(m) of m operations; amortised cost = T(m)/m | n pushes cost fewer than 3n element moves, so O(1) each |
| Accounting (banker's) | Overcharge cheap operations and store the surplus as credit to pay for later expensive ones | charge 3 per push: 1 for the write, 2 saved for copying later |
| Potential (physicist's) | Define a potential Φ ≥ 0 of the whole structure; amortised cost = actual cost + ΔΦ | Φ = 2 × size − capacity |
Dynamic array doubling. A C++ vector or Java ArrayList doubles its capacity when it is full. Pushing 17 items into an array that starts with capacity 1 triggers copies of 1 + 2 + 4 + 8 + 16 = 31 elements; adding the 17 writes gives a total of 48 moves, which is less than 3 × 17 = 51. In general n pushes cost fewer than 3n moves, so each push is O(1) amortised even though one particular push can cost Θ(n).
Complexity theory sorts decision problems (yes/no questions) by the time an algorithm needs, where polynomial means O(nᵏ) for some constant k and n is the length of the input. P is the class of problems a deterministic algorithm solves in polynomial time. NP (nondeterministic polynomial, not ‘non-polynomial’) is the class whose yes-answers can be verified in polynomial time from a certificate: given a proposed tour, checking that it visits every city once and has length ≤ k is easy even though finding one may not be. Equivalently, a nondeterministic algorithm guesses a solution and checks it in polynomial time; a nondeterministic sort guesses each element's position and verifies the order in O(n). Every problem in P is in NP, so P ⊆ NP.
The Cook–Levin theorem (Stephen Cook 1971; Leonid Levin independently, 1973) proved that Boolean satisfiability (SAT) is NP-complete — the first NP-complete problem. Richard Karp (1972) then used reductions to prove 21 classic problems NP-complete, including clique, vertex cover, Hamiltonian cycle, knapsack and graph colouring. Because every NP problem reduces to each NP-complete problem, a polynomial algorithm for any one of them would give P = NP. Whether P = NP is the most famous open question in computer science (a Clay Millennium Prize problem); most researchers believe P ≠ NP.
| Problem | Class | Remark |
|---|---|---|
| Sorting, searching, shortest paths, MST, Euler circuit, 2-SAT, primality | P | primality joined P with the AKS test (2002) |
| SAT, 3-SAT | NP-complete | SAT was the first (Cook–Levin) |
| Clique, independent set, vertex cover | NP-complete | the standard reduction trio |
| Hamiltonian cycle; TSP decision (‘a tour of length ≤ k?’) | NP-complete | the Euler circuit, by contrast, is in P |
| 0/1 knapsack (decision), subset sum, partition | NP-complete | the O(nW) DP is only pseudo-polynomial: W takes just log W bits |
| Graph k-colouring for k ≥ 3 | NP-complete | 2-colouring (bipartite test) is in P |
| TSP optimisation (find the shortest tour) | NP-hard | an optimisation problem, so not in NP as stated |
| Halting problem | NP-hard, undecidable | not in NP at all |
| Region | Contains | Example |
|---|---|---|
| P (inside NP) | problems solvable in polynomial time | sorting, MST, Dijkstra |
| NP-complete (inside NP, also inside NP-hard) | the hardest problems in NP | SAT, vertex cover, TSP decision |
| NP but neither P nor NP-complete | NP-intermediate problems — they exist if P ≠ NP (Ladner, 1975) | suspected: integer factoring, graph isomorphism |
| NP-hard but outside NP | at least as hard as every NP problem, but not a decision problem verifiable in polynomial time | halting problem, TSP optimisation |
Decidable vs undecidable. A problem is decidable if some algorithm halts on every input with the correct yes/no answer; every problem in P or NP is decidable, if only by trying all certificates. Alan Turing (1936) proved the halting problem — does program P halt on input x? — undecidable: if a decider H existed, build D that, given a program P, runs H(P, P) and does the opposite (loops if H says ‘halts’, halts otherwise); running D on itself contradicts whatever H answers. So no algorithm of any running time solves it; it lies outside NP, yet every NP problem reduces to it, which makes it NP-hard but not NP-complete.
Try the problem first, then reveal the working one step at a time.
Solve (a) T(n) = 2T(n/2) + n, (b) T(n) = 4T(n/2) + n, (c) T(n) = 2T(n/2) + n², (d) T(n) = T(2n/3) + 1.
How many times does count++ run in for (i = n; i > 0; i /= 2) for (j = 0; j < i; j++) count++; when n = 16? What is the order of growth in general?
Arrange in increasing order of asymptotic growth: f₁ = 2ⁿ, f₂ = n^(3/2), f₃ = n log₂ n, f₄ = n^(log₂ n).
Moving n discs needs T(n) = 2T(n − 1) + 1 moves with T(1) = 1. Solve the recurrence and find the number of moves for 10 discs.
Find the order of growth of for (i = 1; i <= n; i++) for (j = 1; j <= n; j += i) count++;
Solve T(n) = 3T(n/4) + n log n using the Master theorem.
True or false? Give a reason for each. (a) 2^(n+1) = O(2ⁿ) (b) 2^(2n) = O(2ⁿ) (c) n² = o(n²) (d) log(n!) = Θ(n log n)
A dynamic array starts with capacity 1 and doubles its capacity whenever it is full. How many element copies happen while pushing 33 items, and what is the amortised cost per push?
Give the time and auxiliary-space complexity of int f(int n) { if (n <= 1) return 1; return f(n - 1) + f(n - 1); }. How would you make it linear?
i = n; i > 0; i /= 2 with inner j < i) is Θ(n), not Θ(n log n): multiplying loop bounds overestimates when the inner bound shrinks.14 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.