Skip to content
LeetQuant
F7 Programming and Algorithms Foundations

F7 · Programming and Algorithms Foundations · Lesson 3 of 6

Complexity Analysis

Big-O, Big-Omega and Big-Theta precisely, how to count the work in loops and recursions, the master theorem, amortised analysis of dynamic arrays and space complexity.

18 min

What the notation says

Complexity describes how the work grows with the input size nn, ignoring constant factors and small inputs. For non-negative functions ff and gg:

  • f=O(g)f = O(g) if there are constants c>0c > 0 and n0n_0 with f(n)≤c g(n)f(n) \le c\,g(n) for all n≥n0n \ge n_0 (an upper bound).
  • f=Ω(g)f = \Omega(g) if f(n)≥c g(n)f(n) \ge c\,g(n) for all n≥n0n \ge n_0 (a lower bound).
  • f=Θ(g)f = \Theta(g) if both hold (a tight bound).

So 3n2+10n=Θ(n2)3n^2 + 10n = \Theta(n^2), and it is also O(n3)O(n^3), which is true but uninformative. In interviews "it's O(nlog⁡n)O(n \log n)" is understood as the tight bound; say "worst case", "average" or "amortised" when it matters which one you mean.

A useful feasibility guide for pure Python, which runs a few times 10710^7 simple steps per second:

nnAcceptable complexity
≤10\le 10O(n!)O(n!)
≤20\le 20O(2n)O(2^n)
≤500\le 500O(n3)O(n^3)
≤5,000\le 5{,}000O(n2)O(n^2)
≤106\le 10^6O(nlog⁡n)O(n \log n) or O(n)O(n)

Counting the work in loops

Write the total as a sum over the outer loop of the inner loop's cost, then evaluate the sum.

  • Two nested loops with j from i + 1 to n: ∑i=0n−1(n−1−i)=n(n−1)2=Θ(n2)\sum_{i=0}^{n-1}(n - 1 - i) = \frac{n(n-1)}{2} = \Theta(n^2). Halving the work does not change the class.
  • An inner loop that doubles j until it reaches n runs ⌈log⁡2n⌉\lceil \log_2 n \rceil times.
  • An inner loop that steps through range(0, n, i) runs ⌈n/i⌉\lceil n/i \rceil times, and ∑i=1nn/i=nHn≈nln⁡n\sum_{i=1}^{n} n/i = n H_n \approx n \ln n: the harmonic pattern, Θ(nlog⁡n)\Theta(n \log n).
  • An outer loop that doubles i, with an inner loop of length i, costs 1+2+4+⋯<2n1 + 2 + 4 + \dots < 2n: geometric sums are dominated by their last term.

Worked example

three loops, three answers

Give the tight complexity of each function and confirm it by counting.

def a(n):
    ops = 0
    for i in range(n):
        j = 1
        while j < n:
            ops += 1
            j *= 2
    return ops

def b(n):
    ops, i = 0, 1
    while i < n:
        for _ in range(i):
            ops += 1
        i *= 2
    return ops

def c(n):
    ops = 0
    for i in range(1, n + 1):
        for _ in range(0, n, i):
            ops += 1
    return ops
Show solution

a. The outer loop runs nn times; the inner loop doubles j from 1, so it runs ⌈log⁡2n⌉\lceil \log_2 n \rceil times. Total Θ(nlog⁡n)\Theta(n \log n). For n=1000n = 1000: 1000×10=10,0001000 \times 10 = 10{,}000, and a(1000) returns 10000.

b. The outer loop runs only log⁡2n\log_2 n times, but its cost is 1+2+4+⋯+2k1 + 2 + 4 + \dots + 2^{k} with 2k<n2^k < n, which is less than 2n2n. Total Θ(n)\Theta(n), not Θ(nlog⁡n)\Theta(n \log n). For n=1024n = 1024: 1+2+⋯+512=10231 + 2 + \dots + 512 = 1023, which is what b(1024) returns.

c. The inner loop runs ⌈n/i⌉\lceil n/i \rceil times, so the total is about nHnn H_n. Total Θ(nlog⁡n)\Theta(n \log n). For n=1000n = 1000, c(1000) returns 8053, against nln⁡n≈6908n \ln n \approx 6908; the gap is a lower-order Θ(n)\Theta(n) term (about 0.58n0.58n from Euler's constant, plus up to nn more from rounding each n/in/i up).

The lesson: do not multiply the loop bounds blindly. Sum the actual inner costs.

Recursions and the master theorem

A recursive algorithm's cost satisfies a recurrence. For divide and conquer of the form

T(n)=a T(n/b)+Θ(nd),a≥1, b>1, d≥0,T(n) = a\,T(n/b) + \Theta(n^d), \qquad a \ge 1,\ b > 1,\ d \ge 0,

(aa subproblems of size n/bn/b, plus Θ(nd)\Theta(n^d) work to split and combine) compare dd with the critical exponent log⁡ba\log_b a:

CaseResultIntuition
d>log⁡bad > \log_b aΘ(nd)\Theta(n^d)the top-level work dominates
d=log⁡bad = \log_b aΘ(ndlog⁡n)\Theta(n^d \log n)every level costs the same; log⁡n\log n levels
d<log⁡bad < \log_b aΘ(nlog⁡ba)\Theta(n^{\log_b a})the leaves dominate

The intuition comes from the recursion tree: level kk has aka^k nodes each doing (n/bk)d(n/b^k)^d work, so the level cost is nd(a/bd)kn^d (a/b^d)^k, a geometric series in kk that shrinks, stays flat or grows.

Recurrences that subtract rather than divide are not covered and are best unrolled: T(n)=T(n−1)+Θ(n)T(n) = T(n-1) + \Theta(n) gives Θ(n2)\Theta(n^2) (sum 1+2+⋯+n1 + 2 + \dots + n), and T(n)=2T(n−1)+Θ(1)T(n) = 2T(n-1) + \Theta(1) gives Θ(2n)\Theta(2^n) (a full binary tree of depth nn).

Worked example

applying the master theorem

Solve: (i) binary search, T(n)=T(n/2)+Θ(1)T(n) = T(n/2) + \Theta(1); (ii) merge sort, T(n)=2T(n/2)+Θ(n)T(n) = 2T(n/2) + \Theta(n); (iii) Karatsuba multiplication, T(n)=3T(n/2)+Θ(n)T(n) = 3T(n/2) + \Theta(n); (iv) T(n)=2T(n/2)+Θ(n2)T(n) = 2T(n/2) + \Theta(n^2).

Show solution

(i) a=1a = 1, b=2b = 2, d=0d = 0: log⁡21=0=d\log_2 1 = 0 = d, the balanced case, so Θ(log⁡n)\Theta(\log n).

(ii) a=2a = 2, b=2b = 2, d=1d = 1: log⁡22=1=d\log_2 2 = 1 = d, balanced, so Θ(nlog⁡n)\Theta(n \log n).

(iii) a=3a = 3, b=2b = 2, d=1d = 1: log⁡23≈1.585>1\log_2 3 \approx 1.585 > 1, so the leaves dominate: Θ(nlog⁡23)≈Θ(n1.585)\Theta(n^{\log_2 3}) \approx \Theta(n^{1.585}), better than the schoolbook Θ(n2)\Theta(n^2).

(iv) a=2a = 2, b=2b = 2, d=2d = 2: log⁡22=1<2\log_2 2 = 1 < 2, so the root dominates: Θ(n2)\Theta(n^2). The recursion adds only a constant factor.

Amortised analysis: why append is O(1)

A Python list stores its elements in an array with spare capacity. When the array is full, append allocates a larger one and copies every element across, an O(n)O(n) step. Amortised analysis averages the cost over a whole sequence of operations, with no probability involved.

Suppose capacity starts at 1 and doubles when full. Over nn appends the copies happen at sizes 1,2,4,…1, 2, 4, \dots up to the largest power of two below nn, so the total copying is

1+2+4+⋯+2k<2n.1 + 2 + 4 + \dots + 2^{k} < 2n .

With 1,025 appends the copies cost 1+2+⋯+1024=2047<2×10251 + 2 + \dots + 1024 = 2047 < 2 \times 1025. Total work is O(n)O(n), so each append is O(1)O(1) amortised, though a single append can cost O(n)O(n). Any constant growth factor g>1g > 1 works (the total is below gg−1n\frac{g}{g-1}n); CPython over-allocates by about 12.5% for large lists.

Growing by a fixed amount kk instead does not: the copies are k+2k+3k+⋯≈n2/(2k)k + 2k + 3k + \dots \approx n^2/(2k), which is 49,50049{,}500 element copies for 1,000 appends with k=10k = 10. That is Θ(n)\Theta(n) per append.

Space complexity

Count the auxiliary memory beyond the input, and say whether you include the output. Two hidden costs catch people out:

  • The call stack. A recursion of depth DD uses Θ(D)\Theta(D) stack frames. Recursive binary search uses O(log⁡n)O(\log n) space; the loop version uses O(1)O(1).
  • Slicing copies. a[1:] and a[mid:] build new lists. A recursive binary search written as search(a[mid + 1:], x) copies n/2+n/4+⋯≈nn/2 + n/4 + \dots \approx n elements, so it is Θ(n)\Theta(n) time and memory, not O(log⁡n)O(\log n). Pass indices instead of slices.

Knowledge check

What is the tight complexity of: for i in range(1, n + 1): for j in range(0, n, i): work()?

Knowledge check

Solve T(n) = 4T(n/2) + Θ(n).

Knowledge check

A recursive binary search on a sorted list recurses with search(a[:mid], x) or search(a[mid + 1:], x). What is its running time?

Knowledge check

A dynamic array grows by a fixed 100 slots whenever it is full. What is the amortised cost of one append over n appends?

Key takeaways

  • OO is an upper bound, Ω\Omega a lower bound, Θ\Theta both; say whether you mean worst case, average or amortised.
  • Sum the inner cost over the outer loop: doubling gives log⁡n\log n, harmonic steps give nlog⁡nn \log n, geometric sums are dominated by their last term.
  • Master theorem: compare dd with log⁡ba\log_b a; unroll subtract-by-one recurrences by hand.
  • Geometric growth makes append O(1)O(1) amortised; fixed increments make it O(n)O(n).
  • Count stack depth and hidden copies (slices) in space and time.

Practice problems

Finished reading?

Answer the 4 knowledge checks to complete this lesson (0 done).