What the notation says
Complexity describes how the work grows with the input size , ignoring constant factors and small inputs. For non-negative functions and :
- if there are constants and with for all (an upper bound).
- if for all (a lower bound).
- if both hold (a tight bound).
So , and it is also , which is true but uninformative. In interviews "it's " 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 simple steps per second:
| Acceptable complexity | |
|---|---|
| or |
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
jfromi + 1ton: . Halving the work does not change the class. - An inner loop that doubles
juntil it reachesnruns times. - An inner loop that steps through
range(0, n, i)runs times, and : the harmonic pattern, . - An outer loop that doubles
i, with an inner loop of lengthi, costs : 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 solutionHide solution
a. The outer loop runs times; the inner loop doubles j from 1, so it runs times. Total . For : , and a(1000) returns 10000.
b. The outer loop runs only times, but its cost is with , which is less than . Total , not . For : , which is what b(1024) returns.
c. The inner loop runs times, so the total is about . Total . For , c(1000) returns 8053, against ; the gap is a lower-order term (about from Euler's constant, plus up to more from rounding each 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
( subproblems of size , plus work to split and combine) compare with the critical exponent :
| Case | Result | Intuition |
|---|---|---|
| the top-level work dominates | ||
| every level costs the same; levels | ||
| the leaves dominate |
The intuition comes from the recursion tree: level has nodes each doing work, so the level cost is , a geometric series in that shrinks, stays flat or grows.
Recurrences that subtract rather than divide are not covered and are best unrolled: gives (sum ), and gives (a full binary tree of depth ).
Worked example
applying the master theorem
Solve: (i) binary search, ; (ii) merge sort, ; (iii) Karatsuba multiplication, ; (iv) .
Show solutionHide solution
(i) , , : , the balanced case, so .
(ii) , , : , balanced, so .
(iii) , , : , so the leaves dominate: , better than the schoolbook .
(iv) , , : , so the root dominates: . 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 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 appends the copies happen at sizes up to the largest power of two below , so the total copying is
With 1,025 appends the copies cost . Total work is , so each append is amortised, though a single append can cost . Any constant growth factor works (the total is below ); CPython over-allocates by about 12.5% for large lists.
Growing by a fixed amount instead does not: the copies are , which is element copies for 1,000 appends with . That is 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 uses stack frames. Recursive binary search uses space; the loop version uses .
- Slicing copies.
a[1:]anda[mid:]build new lists. A recursive binary search written assearch(a[mid + 1:], x)copies elements, so it is time and memory, not . 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
- is an upper bound, a lower bound, both; say whether you mean worst case, average or amortised.
- Sum the inner cost over the outer loop: doubling gives , harmonic steps give , geometric sums are dominated by their last term.
- Master theorem: compare with ; unroll subtract-by-one recurrences by hand.
- Geometric growth makes
appendamortised; fixed increments make it . - 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).