DSA Learning Studio · Foundations of Algorithm Analysis

Time & Space Complexity — counting what really grows

Big-O, Ω and Θ from their formal definitions; analysing loops, recursion and divide-and-conquer; amortized costs; the real cost of Python's built-ins — with worked examples, proofs and seven working labs.

Difficulty: Beginner → Intermediate (advanced section: Upper-intermediate) Reading time: ~85 minutes (+ 30 min exercises) Language: Python 3.8+

AChapter introduction

Prerequisites

You should be comfortable writing Python functions, loops and recursion, and using lists and dictionaries. On the maths side you need powers and logarithms (log₂ 1024 = 10) and the idea of a function's graph. No calculus is required; one optional shortcut uses limits.

Learning objectives

After completing this chapter you will be able to:

  1. Define time complexity and space complexity precisely, and explain why we count operations rather than seconds.
  2. Read, use and prove statements in O, Ω and Θ notation with explicit constants c and n₀.
  3. Derive the complexity of single, nested, triangular and halving loops, of recursion, and of divide-and-conquer recurrences (including the Master Theorem).
  4. Distinguish best, average, worst and amortized cost — and input space from auxiliary space and call-stack space.
  5. Predict the cost of everyday Python operations on list, dict, set and deque, and verify predictions with operation counts, timing and memory tracing.
  6. Use complexity to choose between solutions in interviews and production systems, and know when Big-O alone is not enough.
The one-sentence promise Complexity analysis replaces "it ran in 0.3 seconds on my laptop" with a law such as "the work grows like n²", which predicts — before you buy hardware or ship code — what happens when the input becomes 10× or 1,000× larger. [3][5]
How the visuals in this chapter are made This environment has no image-generation model, so every "whiteboard" illustration is drawn in code as SVG with marker-style strokes and handwriting labels. Curves and numbers are computed from the exact formulas, so every value in a figure is correct. All seven interactive labs are fully working. Passages tagged Illustration are my own worked examples rather than claims taken from a source.

BFundamental understanding

What is complexity?

An algorithm consumes two scarce resources: time (how many steps the processor performs) and space (how much memory it occupies while running). Complexity analysis describes how those resource needs grow as a function of the input size n. MIT's 6.006 frames efficiency the same way: running time is measured by counting fixed-time operations, so the answer does not depend on a particular machine [2], and asymptotic ("big-O") notation describes the growth of the runtime without worrying about computers, compilers or implementations [3].

Formal definition The time complexity of an algorithm is a function T(n) giving the number of primitive operations it performs on an input of size n (usually in the worst case), under a fixed model of computation such as the word-RAM [2][1]. The space complexity S(n) is the maximum number of memory cells (words) in use at any moment during the run. Both are classified by their order of growth using asymptotic notation [4][5].
Plain-English definition Time complexity answers: "If I give this program twice as much data, how much longer will it take?" Space complexity answers: "…and how much more memory will it need?" We care about the shape of the growth (flat, straight line, parabola, explosion), not the exact number of milliseconds.

Why the concept exists

Timing a program with a stopwatch tells you about that program on that machine with that input. Princeton's Sedgewick and Wayne list the reasons we analyse algorithms instead: to predict performance, compare algorithms, provide guarantees and understand the theory — with the primary practical reason being to avoid performance bugs [6]. Their N-body example makes the point: a brute-force simulation needs about n² steps, which limited what scientists could simulate until faster algorithms arrived [6].

A short, verifiable history

The symbol O predates computers. Donald Knuth traced it to Paul Bachmann's 1894 number-theory book, after which Edmund Landau popularised it (and introduced little-o) [13]. In 1976 Knuth argued in SIGACT News that computer scientists also need notation for lower bounds and tight bounds, and proposed the now-standard Ω and Θ definitions [13]. Today these definitions are the ones taught in CLRS and in university courses [1][4].

Fundamental principles (introduced one term at a time)

TermMeaning
Input size nThe quantity that grows: number of list elements, characters, vertices + edges, bits of a number…
Primitive operationA step that costs O(1) in the model: integer and logical arithmetic, comparisons, bitwise operations, reading or writing one machine word [2].
Word-RAM modelA machine whose words are w bits, with w ≥ log₂ n so that every memory address fits in one word [2].
Order of growthThe dominant term of T(n) with constants dropped: e.g. T(n) ∼ c·f(n), where f(n) is typically log n, n, n log n, n², n³ [5].
AsymptoticConcerned with behaviour "for all sufficiently large n"; small inputs are ignored [4].
Worst / best / average caseThe maximum, minimum, or expected cost over all inputs of size n [1][4].
Amortized costTotal cost of a sequence of k operations divided by k [7].
Auxiliary spaceExtra memory the algorithm allocates beyond the input itself (variables, copies, call stack).

CThe problem complexity analysis solves

Problem description

Input: two or more correct algorithms for the same task, plus an expected range of input sizes. Output: a prediction of how each will scale — and therefore which one to ship. Constraints: the prediction must be independent of hardware, language and compiler, and must hold as n grows beyond what we can test.

Why the naive approach (benchmarking only) falls short

Measuring wall-clock time is valuable — Princeton teaches an empirical "doubling" method in which you time the program at n and 2n and inspect the ratio [5] — but timing alone cannot tell you why a program is slow, cannot be done before the code exists, and cannot safely be extrapolated from small tests to 1000× larger production inputs. Wall-clock numbers also mix in effects of the machine, the interpreter and the cache that asymptotic analysis deliberately abstracts away [3].

How complexity analysis improves the situation

By counting the dominant operations as a function of n, we obtain a machine-independent "law" such as T(n) ∼ n³/6. Princeton shows this for the brute-force 3-SUM program, whose inner if executes exactly n(n−1)(n−2)/6 times, i.e. ∼ n³/6 [5]. A cubic law immediately predicts that doubling n multiplies running time by about 2³ = 8 — which is exactly what their measurements show [5].

Real-world analogy Illustration You must find a friend's name in a 1,000-page phone book. Reading every page in order is a linear strategy — 10× more pages means 10× more work. Opening the book in the middle, deciding which half the name is in, and repeating is a logarithmic strategy — 1,000 pages need about 10 halvings, and a million pages only about 20. Neither strategy depends on how fast you read; the difference is in the shape of the work. That shape is what complexity captures.

DVisual whiteboard explanations

Before any formulas, let's draw the ideas the way a professor would on a whiteboard. Colours keep the same meaning throughout the chapter.

Blue — input data, arrays, memory blocks Green — results, efficient / successful Red — wasted work, errors, dangerous growth Orange — active step, current pointer, time Purple — relationships, recursion, the call stack Black — definitions & labels
Figure D.1 · Concept introductionThe two budgets of every algorithm
input of size ntime = stepsspace = memory / outputthe question we ask
7391… input · size n algorithm loops, calls, comparisons output TIME · how many steps? T(n) count operations, not seconds SPACE · peak memory S(n) variables + copies + stack ? How do T(n) and S(n) grow as n grows
Step by step. (1) Blue input of size n enters. (2) The algorithm performs steps — the orange clock counts them; that count, as a function of n, is T(n). (3) While running it occupies working memory — the green blocks; the peak amount is S(n). Technical interpretation: complexity analysis studies the growth rate of T and S, not their value at a single n [3][5].
Figure D.2 · Time complexity visualizationGrowth curves on the whiteboard (n from 1 to 20)
1 (constant)log₂ nnn log₂ nn²2ⁿ
0255075100 15101520 nsteps 2ⁿ explodes! n² n log n n log n 1 (flat) at n=20: 2ⁿ ≈ 1,048,576
What to notice. (1) Constant and logarithmic curves hug the axis. (2) The straight line n and the slightly-bent n log n stay manageable. (3) n² leaves the board at n = 10; 2ⁿ leaves it at n ≈ 6.6. Technical interpretation: for large n, the order of growth dominates constant factors — which is why MIT's 6.006 shows exponential time being hopeless already at n = 1000 while log-linear time finishes in microseconds [2].
Figure D.3 · Comparison of growth classesThe complexity staircase (operations at n = 1,000)
scales to huge inputsfine for moderate nonly tiny inputs
O(1) O(log n) O(n) O(n log n) O(n²) O(2ⁿ) O(n!) ≈ 10 ops 1,000linear scan ≈ 10,000merge sort 1,000,000all pairs ≈ 1.07 × 10³⁰¹all subsets ≈ 4 × 10²⁵⁶⁷all orderings 1 · index a[i] binary search
Reading the staircase. Each step to the right is a fundamentally worse growth class. At n = 1,000: log₂ n ≈ 10, n log₂ n ≈ 10⁴, n² = 10⁶, 2ⁿ ≈ 1.07 × 10³⁰¹ and n! ≈ 4.02 × 10²⁵⁶⁷ (computed values). Technical interpretation: these are the standard order-of-growth classes used by Princeton's algorithms course and CLRS [5][6][1]; the algorithm names are representative members of each class.
Figure D.4 · Step-by-step executionFour loop shapes and the work they do
input cells(i, j) pair visited = one unit of workcurrent index idiscarded half
① for i in range(n) 01234567igreen = done n iterations → Θ(n) one pass, constant work each ② for i … for j in range(n) j →i n · n → Θ(n²) every cell ③ for i … for j in range(i+1, n) j →i n(n−1)/2 → still Θ(n²) half the grid ≠ a better class ④ while i > 1: i //= 2 168421 ⌊log₂ n⌋ halvings → Θ(log n)
Step by step. ① A single loop touches each of the n cells once. ② Two independent nested loops visit every (i, j) pair: n² green cells. ③ Starting j at i+1 visits only the upper triangle: n(n−1)/2 cells — half as many, but the leading term is still n²/2, so the class is unchanged. ④ A loop that halves its counter runs ⌊log₂ n⌋ times (4 times for n = 16). Technical interpretation: loop analysis is just summation; the ∑ rules appear in Section G [1][4].

EInteractive lab

These visualisers run entirely in your browser. Every button does real work: values are computed live, not pre-recorded. More visualisers appear in later sections where they fit the explanation (call stack in F, the formal definition in G, amortized arrays in H, and a self-check quiz in M).

Lab 1Growth-rate explorer
Toggle functions, stretch the x-axis, switch to a log scale, and read off how long each would take at a given n.
Times are Illustration estimates: operations ÷ assumed speed, with every constant factor set to 1. Real programs differ by constant factors — the point is the dramatic spread between classes.
Lab 2Loop step-counter
Pick a code pattern and n, then play or step through it. The orange line is executing; each green cell is one unit of work.
work done0
formula predicts–

FInternal working: how cost is actually counted

The machine model underneath

To count "steps", we need to agree on what one step is. Courses such as MIT 6.006 use the word-RAM: memory is an array of w-bit words, and integer arithmetic, logical and bitwise operations, comparisons, and reading or writing a word at a given address each take O(1) time [2]. Because w ≥ log₂ n, an index into an array of n items fits in one word, which is exactly why a[i] is a constant-time operation [2].

The counting procedure

  1. Choose the input size n. For a list it is its length; for a graph, usually V and E; for a number, its number of bits.
  2. Choose the basic operation — the one in the innermost loop. Princeton's method focuses on the most frequently executed instructions, since time outside the inner loop is relatively insignificant [5].
  3. Write the count as a sum (loops) or a recurrence (recursion).
  4. Simplify to a closed form, e.g. ∑ᵢ₌₀ⁿ⁻¹ (n−1−i) = n(n−1)/2.
  5. Keep the leading term, drop its constant: n(n−1)/2 ∼ n²/2 ⟹ Θ(n²) [5][1].

Worked example: line-by-line cost of find_max

This is the CLRS-style "cost × times" table [1]. Let cₖ be the constant cost of line k.

def find_max(a):          # n = len(a) ≥ 1
    best = a[0]              # line 1
    for x in a[1:]:          # line 2
        if x > best:         # line 3
            best = x         # line 4
    return best              # line 5
LineCostTimes executedComment
1c₁1one read, one write
2c₂n (n−1 iterations + loop exit); slicing a[1:] also copies n−1 referencesPython slice is O(j−i) [9]
3c₃n − 1one comparison per remaining element
4c₄between 0 (best) and n − 1 (worst: increasing input)data-dependent
5c₅1

Summing gives T(n) = A·n + B for constants A, B in every case, so T(n) = Θ(n). Note the hidden detail: the slice a[1:] allocates a new list of n−1 references, making the auxiliary space Θ(n) instead of Θ(1). Iterating with range(1, len(a)) avoids that copy.

Memory representation: where does space go?

A running program's memory splits into the input (given to us), auxiliary data (variables, new lists, hash tables we build), and the call stack (one frame per active function call). Space complexity usually means the auxiliary part plus the stack. In CPython a list is internally an array of references to objects [10], and the interpreter limits recursion depth with a configurable limit that exists to prevent infinite recursion from overflowing the C stack and crashing Python [11].

Figure F.1 · Memory representationInput space, auxiliary space and the call stack
input array (not counted as auxiliary)auxiliary variablescall-stack framescurrently executing frame
input a = [4, 8, 15, 16] 481516 [0][1][2][3] sum_iterative(a) total = 43x = 16 frame: sum_iterative 2 variables, 1 frame → O(1) auxiliary space sum_recursive(a, i) sum_recursive(a, 4) → 0sum_recursive(a, 3)sum_recursive(a, 2)sum_recursive(a, 1)sum_recursive(a, 0) callspile up base case n + 1 = 5 frames alive at once → O(n) auxiliary space (call stack)
Step by step. (1) Both functions read the same blue input; it is not counted as auxiliary space. (2) The loop version keeps two green variables no matter how long the list is: O(1). (3) The recursive version cannot finish sum_recursive(a, 0) until (a, 1) returns, and so on, so n + 1 purple frames are alive at the deepest point: O(n). Technical interpretation: recursion depth is space. With CPython's default limit of 1,000 frames (see sys.getrecursionlimit() [11]), sum_recursive on 100,000 items raises RecursionError, which we demonstrate in Section I.
Lab 4Recursion tree & call stack (Fibonacci)
Time = number of calls (nodes). Space = deepest call stack. Compare plain recursion with memoization.
executing nowwaiting on the stackreturned (value shown)answered from memorepeated sub-problem (naive)
call stack (top ↑)
calls so far0
current depth0
max depth (space)0
total calls (time)–

Notice what the lab shows: the naive tree has exponentially many nodes (the number of calls for fib(n) is 2·F(n+1) − 1, e.g. 177 calls for n = 10 in our Python run), yet the stack never gets deeper than about n frames, because only one root-to-leaf path is alive at a time. Memoization collapses time to linear (2n − 1 calls) while space stays linear. Time and space are different budgets, and recursion spends them differently.

Edge cases that change the answer

GMathematical foundation

The three core definitions

Let f, g be functions from non-negative integers to non-negative reals. The definitions below are those of CLRS and Stanford CS161 [1][4]:

Big-O — an upper bound f(n) = O(g(n)) ⟺ there exist constants c > 0 and n₀ such that 0 ≤ f(n) ≤ c·g(n) for all n ≥ n₀.
Big-Omega — a lower bound f(n) = Ω(g(n)) ⟺ there exist c > 0 and n₀ such that 0 ≤ c·g(n) ≤ f(n) for all n ≥ n₀.
Big-Theta — a tight bound f(n) = Θ(g(n)) ⟺ f(n) = O(g(n)) and f(n) = Ω(g(n)); equivalently there exist c₁, c₂ > 0 and n₀ with c₁·g(n) ≤ f(n) ≤ c₂·g(n) for all n ≥ n₀.

MIT's Mathematics for Computer Science text stresses that Big-O gives an upper bound on growth and is the most frequently used asymptotic notation [14]. The "=" sign is a long-standing abuse of notation: O(g) is really a set of functions, and MIT's 6.006 recitation notes call f(x) = Θ(x²) "really misleading" for that reason [3].

Figure G.1 · Mathematical definitionThe Θ "sandwich": f(n) = n² + 3n + 12 is Θ(n²)
f(n) — our running timec₂·g(n) = 2n² (upper bread)c₁·g(n) = ½n² (lower bread)n₀ ≈ 5.27
n₀ n 2n² f(n) ½ n² here f > 2n² (small n ignored) for all n ≥ n₀ : ½n² ≤ f(n) ≤ 2n² 036912
Step by step. (1) For small n the blue curve pokes above the red upper bound — allowed, because the definition only cares about n ≥ n₀. (2) Solving n² + 3n + 12 ≤ 2n² gives n² − 3n − 12 ≥ 0, i.e. n ≥ (3 + √57)/2 ≈ 5.27. (3) The lower bound ½n² ≤ f(n) holds for every n ≥ 0. (4) In the shaded region f is trapped between the two, so f = Θ(n²). Technical interpretation: constants c₁ = ½, c₂ = 2, n₀ = 6 witness the definition [1][4].

Worked proofs

Claim 1. 3n² + 5n + 2 = O(n²). Proof. For n ≥ 1 we have 5n ≤ 5n² and 2 ≤ 2n², so 3n² + 5n + 2 ≤ 10n². Choose c = 10, n₀ = 1. ∎ (Many witnesses work: c = 4 with n₀ = 6 also works, because n² − 5n − 2 ≥ 0 once n ≥ 5.37.)

Claim 2. 3n² + 5n + 2 = Ω(n²). Proof. For n ≥ 0, 3n² + 5n + 2 ≥ 3n². Choose c = 3, n₀ = 0. ∎ Together, Claims 1 and 2 give Θ(n²).

Claim 3. n² ≠ O(n). Proof by contradiction. Suppose n² ≤ c·n for all n ≥ n₀. Dividing by n gives n ≤ c for all n ≥ n₀, which fails at n = max(n₀, ⌈c⌉ + 1). ∎

The limit test (a shortcut) If L = limn→∞ f(n)/g(n) exists, then L = 0 ⟹ f = o(g) (hence O(g)); 0 < L < ∞ ⟹ f = Θ(g); L = ∞ ⟹ f = ω(g) (hence Ω(g)) [16]. Little-o and little-ω are the strict versions of O and Ω: f = o(g) means f grows strictly slower [16][13].
Lab 5Prove it yourself: find c and n₀
Pick f(n) = a·n² + b·n + d and a comparison function g(n). Slide c and n₀ until the bound holds for every integer n from n₀ to 10,000.
f(n)c·g(n) where the bound holdsn ≥ n₀ where it failsn₀

Rules that make analysis fast

RuleStatementExample
Constant factorsO(k·f) = O(f) for any constant k > 07n = O(n)
Sum ruleO(f) + O(g) = O(max(f, g))sorting then scanning: n log n + n = O(n log n)
Product ruleO(f)·O(g) = O(f·g)a loop of n iterations each doing O(log n) work: O(n log n)
Transitivityf = O(g) and g = O(h) ⟹ f = O(h)log n = O(n), n = O(n²) ⟹ log n = O(n²)
Log basesloga n = logb n / logb a, a constant factor apartO(log₂ n) = O(log₁₀ n) = O(log n)
Hierarchy1 ≺ log n ≺ √n ≺ n ≺ n log n ≺ n² ≺ n³ ≺ 2ⁿ ≺ n!any polynomial is o(2ⁿ); any power of log n is o(nε)

These follow directly from the definitions and are developed in CLRS Chapter 3 and MIT's asymptotics notes [1][14].

Summations for loops

∑i=1n i = n(n+1)/2 = Θ(n²)  ·  ∑i=0k 2i = 2k+1 − 1  ·  ∑i=1n 1/i = ln n + O(1)

The arithmetic series explains triangular loops (Figure D.4 ③). The geometric series explains why doubling a dynamic array costs O(n) in total (Section H) [7]. The harmonic series appears when the inner loop runs n/i times (e.g. sieve-like loops) [1].

Recurrences for recursion

RecurrenceTypical algorithmSolution
T(n) = T(n/2) + O(1)binary searchΘ(log n)
T(n) = T(n−1) + O(1)recursive sum / factorialΘ(n)
T(n) = 2T(n/2) + Θ(n)merge sortΘ(n log n) [4]
T(n) = T(n−1) + Θ(n)selection / insertion sort (worst)Θ(n²)
T(n) = 2T(n−1) + O(1)Towers of Hanoi, all subsetsΘ(2ⁿ)
T(n) = T(n−1) + T(n−2) + O(1)naive FibonacciΘ(φⁿ), φ ≈ 1.618

The Master Theorem

For divide-and-conquer recurrences T(n) = a·T(n/b) + f(n) with a ≥ 1, b > 1, compare f(n) with the "watershed" nlogb a, the total cost of the leaves of the recursion tree [8][1]:

CaseConditionResultExample
1 · leaves dominatef(n) = O(nlogba − ε) for some ε > 0Θ(nlogba)T(n) = 8T(n/2) + n² ⟹ Θ(n³)
2 · balancedf(n) = Θ(nlogba logk n), k ≥ 0Θ(nlogba logk+1 n)merge sort: a = b = 2, f = n ⟹ Θ(n log n)
3 · root dominatesf(n) = Ω(nlogba + ε) and a·f(n/b) ≤ k·f(n) for some k < 1Θ(f(n))T(n) = 2T(n/2) + n² ⟹ Θ(n²)
Figure G.2 · Recursion treeRecursion tree for merge sort: T(n) = 2T(n/2) + n
recursive calls (tree edges)sub-problem of the given sizework per leveltotal
nn/2n/2n/4n/4n/4n/4 … n leaves of size 1 n2·(n/2) = n4·(n/4) = nn·1 = n log₂ n + 1 levels total = n · (log₂ n + 1) = Θ(n log n)
Step by step. (1) The root does n work to merge two halves. (2) Level i has 2i sub-problems of size n/2i, so each level costs n. (3) Halving reaches size 1 after log₂ n levels. (4) Multiply: n per level × (log₂ n + 1) levels. Technical interpretation: this is exactly Stanford CS161's analysis — "total number of operations = (operations per level) · (number of levels)" — yielding O(n log n) for every input [4].

HOperations and complexity analysis

Best, average, worst — and why worst case is the default

Stanford CS161 frames worst-case analysis as a game against an adversary who picks the input: a worst-case guarantee holds for every input of size n, which makes it a strong and robust promise [4]. Average-case analysis needs an assumed input distribution (e.g. "every permutation equally likely") [1]. Best case is rarely useful on its own, since almost any algorithm can be made fast on some lucky input.

Common confusionBig-O ≠ worst case and Ω ≠ best case. O, Ω and Θ are bounds on functions; best/worst/average choose which function you are bounding. "Insertion sort's best case is Θ(n) and its worst case is Θ(n²)" uses Θ for both [1].

Master table of classic operations

Assumptions: n = number of elements; arrays are random-access; "sorted" is stated where needed; hash tables assume a good hash function.

OperationBestAverageWorstAuxiliary space
Access a[i] (array / Python list)Θ(1)Θ(1)Θ(1)Θ(1)
Linear search (unsorted)Θ(1)Θ(n)Θ(n)Θ(1)
Binary search (sorted)Θ(1)Θ(log n)Θ(log n)Θ(1) iterative · Θ(log n) recursive
Find max / sumΘ(n)Θ(n)Θ(n)Θ(1)
Insertion sortΘ(n) (sorted input)Θ(n²)Θ(n²)Θ(1)
Merge sortΘ(n log n)Θ(n log n)Θ(n log n)Θ(n)
Python list.sort() / sorted()O(n) on already-sorted or reverse-sorted inputO(n log n)O(n log n) [9]O(n)
Hash lookup / insert (dict, set)O(1)O(1)O(n) if all keys collide [9]O(1) per op
Dynamic array append (list.append)O(1)O(1) amortizedO(n) for one resize [9]O(n) during resize
Brute-force duplicate check (all pairs)Θ(1) (dup at front)—Θ(n²)Θ(1)
Naive recursive FibonacciΘ(φⁿ) calls on every input nΘ(n) stack

Reasoning: binary search halves the interval each comparison (Θ(log n)); insertion sort's inner loop shifts 0 elements on sorted input and up to i elements on reverse-sorted input, giving ∑i = Θ(n²) [1]; merge sort is covered by Figure G.2 [4]; Python's sort is adaptive, so sorted or reverse-sorted input needs only O(n) comparisons [9].

Theory vs. actual Python behaviour

The CPython documentation publishes complexities for built-in types. These are the entries you will use most [9][10]:

TypeOperationCostNote
listl[k], l[k] = x, len(l)O(1)array of references [10]
l.append(x)O(1) amortizedoccasional O(n) resize [9]
l.pop() (last) vs l.pop(k)O(1) vs O(n − k)pop(0) shifts every element
l.insert(k, x), del l[k]O(n − k)elements after k move
x in l, min(l), max(l)O(n)linear scan
l[i:j]O(j − i)creates a copy
l.sort()O(n log n)O(n) if already ordered
dict / setk in d, d[k], d[k] = v, del d[k], s.addO(1) averageO(n) worst case when every key hashes to the same value [9]
s1 & s2O(min(len(s1), len(s2)))iterates the smaller set
collections.dequeappend, appendleft, pop, popleftO(1)use instead of list.pop(0) for queues [12]
Theory vs practice Asymptotic notation hides constants. A pure-Python loop executes many bytecode instructions per "step", while built-ins such as sum() or sorted() run their loops in C, so two Θ(n) solutions can differ by a large constant factor. MIT's 6.042 notes warn that constants hidden by O can matter in practice [14], and the Python wiki notes other implementations may differ from CPython [10]. Use complexity to choose the class; use measurement to choose between solutions in the same class.

Amortized analysis: why append is O(1) although resizing is O(n)

Amortized cost = total cost of a sequence of k operations ÷ k [7]. It is a worst-case guarantee about sequences, not an average over random inputs. MIT 6.046 presents three techniques — the aggregate, accounting and potential methods — and applies them to table doubling [7][18].

Aggregate method. Start with capacity 1 and double when full. Inserting n items triggers copies of 1 + 2 + 4 + … + 2⌊log₂(n−1)⌋ < 2n elements (geometric series), plus n writes, so the total is < 3n and each append costs O(1) amortized [7].

Accounting method. Charge every insert 3 coins: one pays for the write, two are saved. When the table of size m doubles, the m/2 items inserted since the last doubling have saved m coins — exactly enough to move all m items [7].

CPython's actual policy is not exact doubling: the list implementation over-allocates proportionally to the list size, "mild" but enough for linear-time amortized behaviour over a long sequence of appends [19][9]. Any growth by a constant factor gives amortized O(1); growth by a constant amount (e.g. +10 slots) gives Θ(n²) total.

Lab 6Dynamic array: watch amortization happen
Each append writes one element (cost 1). When the array is full it first allocates double the capacity and copies everything (cost = number of copies).
just appendedcopied during resizestored elementfree capacity
size n0
capacity1
total cost0
cost / append–

Time–space trade-offs

Many speed-ups buy time with memory. The duplicate check is the textbook case: the all-pairs version uses Θ(n²) time and Θ(1) space, while the hash-set version uses O(n) average time and O(n) space (Section I). Memoization (Lab 4) stores Θ(n) results to turn exponential time into linear time. Prefix sums store n + 1 numbers so that any range sum takes O(1). The reverse trade also exists: the iterative Fibonacci keeps only two variables, Θ(1) space, by recomputing rather than storing.

IPython implementation

The companion module below implements every example in this chapter from scratch, instruments it with an operation counter so you can see growth rates, and measures time and memory with the standard library. It was executed with CPython 3 to produce the outputs shown.

I.1 The instrumentation idea

Instead of a stopwatch, each function receives an OpCounter and calls c.tick() once per basic operation (the comparison in the innermost loop). This is the "count the inner loop" method from Princeton [5] turned into code.

class OpCounter:
    """Counts 'basic operations' so we can see growth without a stopwatch."""
    def __init__(self):
        self.ops = 0
    def tick(self, k=1):
        self.ops += k

I.2 One function per complexity class

def get_first(a, c):                 # Θ(1): one index, independent of n
    c.tick()
    return a[0] if a else None

def binary_search(a, target, c):     # O(log n): interval halves each pass
    lo, hi = 0, len(a) - 1                 # invariant: target, if present, is in a[lo..hi]
    while lo <= hi:
        c.tick()
        mid = (lo + hi) // 2
        if a[mid] == target:
            return mid
        if a[mid] < target:
            lo = mid + 1                    # discard left half
        else:
            hi = mid - 1                    # discard right half
    return -1

def has_duplicate_quadratic(a, c):   # O(n²) time, O(1) extra space
    n = len(a)
    for i in range(n):
        for j in range(i + 1, n):         # triangular loop: n(n-1)/2 pairs
            c.tick()
            if a[i] == a[j]:
                return True
    return False

def has_duplicate_set(a, c):         # O(n) average time, O(n) extra space
    seen = set()
    for x in a:
        c.tick()
        if x in seen:                    # O(1) average membership test
            return True
        seen.add(x)
    return False

Line notes. In binary_search, the loop invariant "if the target is present it lies in a[lo..hi]" is what makes discarding half the array safe; each iteration shrinks hi − lo + 1 to at most half, so there are at most ⌊log₂ n⌋ + 1 iterations [1]. (lo + hi) // 2 cannot overflow in Python because integers have unbounded precision; in fixed-width languages write lo + (hi − lo) // 2. In has_duplicate_set, x in seen and seen.add(x) are O(1) on average and O(n) in the worst case [9].

I.3 Space: recursion versus iteration, and exponential versus linear

def sum_recursive(a, i=0):           # O(n) time, O(n) call-stack space
    if i == len(a):                     # base case
        return 0
    return a[i] + sum_recursive(a, i + 1)

def sum_iterative(a):                # O(n) time, O(1) auxiliary space
    total = 0
    for x in a:
        total += x
    return total

def fib_naive(n, c):                 # Θ(φⁿ) time, Θ(n) stack
    c.tick()
    if n < 2:
        return n
    return fib_naive(n - 1, c) + fib_naive(n - 2, c)

def fib_iter(n):                     # Θ(n) time, Θ(1) auxiliary space
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

I.4 A dynamic array from scratch, with amortized accounting

class DynamicArray:
    """Doubling array: append is O(1) amortized, O(n) worst case."""
    def __init__(self):
        self._cap, self._n = 1, 0
        self._data = [None] * self._cap
        self.copies = 0                   # element moves caused by resizing
    def __len__(self):
        return self._n
    def __getitem__(self, i):
        if not 0 <= i < self._n:           # error handling: reject out-of-range
            raise IndexError("DynamicArray index out of range")
        return self._data[i]
    def append(self, x):
        if self._n == self._cap:         # full → grow by a constant FACTOR
            self._resize(2 * self._cap)
        self._data[self._n] = x
        self._n += 1
    def _resize(self, new_cap):         # Θ(n): copy every element
        new = [None] * new_cap
        for k in range(self._n):
            new[k] = self._data[k]
            self.copies += 1
        self._data, self._cap = new, new_cap

I.5 Measuring instead of guessing

The standard library provides time.perf_counter/timeit for timing [17] and tracemalloc for tracing memory allocations, including the peak size of traced blocks [20]. The doubling experiment reproduces Princeton's method: if T(n) ∼ c·nb, then T(2n)/T(n) → 2b [5].

def peak_bytes(fn, *args):
    tracemalloc.start()
    fn(*args)
    _, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return peak

def doubling_experiment(fn, sizes):
    prev, rows = None, []
    for n in sizes:
        data = list(range(n))
        t0 = time.perf_counter(); fn(data); t = time.perf_counter() - t0
        rows.append((n, t, None if prev is None else t / prev))
        prev = t
    return rows

I.6 Sample run — actual output

Running the complete module (I.10) printed the following. Timing numbers vary by machine; the ratios are what matter.

== Operation counts ==
n=  8  O(1)=1  O(log n)=3  O(n)=7  O(n log n)=12  O(n^2)=28
n= 16  O(1)=1  O(log n)=4  O(n)=15  O(n log n)=32  O(n^2)=120
n= 32  O(1)=1  O(log n)=5  O(n)=31  O(n log n)=80  O(n^2)=496
n= 64  O(1)=1  O(log n)=6  O(n)=63  O(n log n)=192  O(n^2)=2016

== Fibonacci calls ==
fib(10)=55  naive calls=177  memo calls=19  iter=55
fib(20)=6765  naive calls=21891  memo calls=39  iter=6765
fib(25)=75025  naive calls=242785  memo calls=49  iter=75025

== Duplicates ==
False 499500 False 1000

== Recursion depth ==
limit: 1000
sum_iterative(10**5): 4999950000
sum_recursive(10**5): RecursionError: maximum recursion depth exceeded

== Dynamic array ==
n=     8 copies=     7  (n+copies)/n = 1.875
n=    16 copies=    15  (n+copies)/n = 1.938
n=  1000 copies=  1023  (n+copies)/n = 2.023
n=100000 copies=131071  (n+copies)/n = 2.311

== Peak memory (tracemalloc) ==
list(range(10**5)) bytes ~ 3991952
sum generator  bytes ~ 456

== Doubling experiment: quadratic dup check ==
n=  500 t=0.0063s ratio=None
n= 1000 t=0.0274s ratio=4.36
n= 2000 t=0.1059s ratio=3.86
Reading the output
  • Each doubling of n adds 1 to the binary-search count, roughly doubles the linear count, and roughly quadruples the quadratic count (28 → 120 → 496 → 2016 is exactly n(n−1)/2).
  • Naive Fibonacci calls grow ≈ 11× from n = 20 to 25 (φ⁵ ≈ 11.09); memoized calls grow by 10 (2n − 1).
  • For 1,000 distinct items the brute-force check does 499,500 comparisons; the set version does 1,000.
  • (n + copies)/n stays below 3 — the amortized bound from Section H.
  • The quadratic routine's time ratio is ≈ 4 when n doubles, matching 2² [5].
  • Materialising list(range(10⁵)) peaks near 4 MB; summing a generator peaks under 1 KB — Θ(n) vs Θ(1) space.

I.7 Dry-run tables

Dry run 1 · binary_search([1, 3, 5, 7, 9, 11, 13, 15], 12)

Iterationlohimida[mid]Decision
107377 < 12 → lo = 4
24751111 < 12 → lo = 6
36761313 > 12 → hi = 5
—65——lo > hi → return −1 (3 comparisons ≤ ⌊log₂ 8⌋ + 1 = 4)

Dry run 2 · has_duplicate_set([3, 1, 4, 1, 5])

Stepxseen beforex in seen?Action
13{}Falseadd 3
21{3}Falseadd 1
34{1, 3}Falseadd 4
41{1, 3, 4}Truereturn True after 4 ticks

Dry run 3 · DynamicArray: appending 1 … 9

Append #cap beforeResize?Copies this stepTotal copiesTotal cost (writes + copies)
11no001
21→ 2113
32→ 4236
44no037
54→ 84712
6–88no0715
98→ 1681524 (24 / 9 ≈ 2.67 < 3)

I.8 Edge cases and error handling

I.9 Built-in alternatives and how they compare

TaskFrom scratch (this chapter)Built-inComplexity
Maximumfind_maxmax(a)Θ(n) both; built-in loop runs in C [9]
Search sorted listbinary_searchbisect.bisect_left(a, x)O(log n) [22]
Membershiplinear scanx in set_O(n) list vs O(1) average set [9]
Sortingmerge_sortsorted(a), a.sort()O(n log n); O(n) on presorted input [9]
Memoizationdict-based fib_memo@functools.cache / lru_cachetrades O(n) memory for time [23]
Queuelist.pop(0)collections.deque.popleft()O(n) vs O(1) [12]
Timingperf_counter looptimeit— [17]

I.10 The complete, runnable module

Save as complexity_examples.py and run with python3 complexity_examples.py.

"""Chapter: Time and Space Complexity — runnable companion code."""
import sys, time, tracemalloc
from functools import lru_cache

# ---------- 1. Instrumented step counter ----------
class OpCounter:
    """Counts &#x27;basic operations' so we can see growth without a stopwatch."""
    def __init__(self):
        self.ops = 0
    def tick(self, k=1):
        self.ops += k

def get_first(a, c):                 # O(1)
    c.tick()
    return a[0] if a else None

def find_max(a, c):                  # Θ(n)
    if not a:
        raise ValueError("find_max() of empty sequence")
    best = a[0]
    for x in a[1:]:
        c.tick()                     # one comparison per remaining element
        if x > best:
            best = x
    return best

def binary_search(a, target, c):     # O(log n)
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        c.tick()
        mid = (lo + hi) // 2
        if a[mid] == target:
            return mid
        if a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

def merge_sort(a, c):                # Θ(n log n) time, Θ(n) aux space
    if len(a) <= 1:
        return a[:]
    mid = len(a) // 2
    left, right = merge_sort(a[:mid], c), merge_sort(a[mid:], c)
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        c.tick()
        if left[i] <= right[j]:
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    out.extend(left[i:]); out.extend(right[j:])
    return out

def has_duplicate_quadratic(a, c):   # O(n^2) time, O(1) aux space
    n = len(a)
    for i in range(n):
        for j in range(i + 1, n):
            c.tick()
            if a[i] == a[j]:
                return True
    return False

def has_duplicate_set(a, c):         # O(n) average time, O(n) aux space
    seen = set()
    for x in a:
        c.tick()
        if x in seen:
            return True
        seen.add(x)
    return False

# ---------- 2. Exponential vs linear: Fibonacci ----------
def fib_naive(n, c):                 # Θ(φ^n) time, Θ(n) stack space
    c.tick()
    if n < 2:
        return n
    return fib_naive(n - 1, c) + fib_naive(n - 2, c)

def fib_memo(n, c, memo=None):       # Θ(n) time, Θ(n) space
    if memo is None:
        memo = {}
    c.tick()
    if n < 2:
        return n
    if n in memo:
        return memo[n]
    memo[n] = fib_memo(n - 1, c, memo) + fib_memo(n - 2, c, memo)
    return memo[n]

def fib_iter(n):                     # Θ(n) time, Θ(1) aux space
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

# ---------- 3. Space: recursion stack vs loop ----------
def sum_recursive(a, i=0):           # O(n) call-stack space
    if i == len(a):
        return 0
    return a[i] + sum_recursive(a, i + 1)

def sum_iterative(a):                # O(1) auxiliary space
    total = 0
    for x in a:
        total += x
    return total

# ---------- 4. Dynamic array with amortized-cost accounting ----------
class DynamicArray:
    """Doubling array: append is O(1) amortized, O(n) worst case."""
    def __init__(self):
        self._cap, self._n = 1, 0
        self._data = [None] * self._cap
        self.copies = 0              # element moves caused by resizing
    def __len__(self):
        return self._n
    def __getitem__(self, i):
        if not 0 <= i < self._n:
            raise IndexError("DynamicArray index out of range")
        return self._data[i]
    def append(self, x):
        if self._n == self._cap:
            self._resize(2 * self._cap)
        self._data[self._n] = x
        self._n += 1
    def _resize(self, new_cap):
        new = [None] * new_cap
        for k in range(self._n):
            new[k] = self._data[k]
            self.copies += 1
        self._data, self._cap = new, new_cap

def peak_bytes(fn, *args):
    tracemalloc.start()
    fn(*args)
    _, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return peak

def doubling_experiment(fn, sizes):
    prev = None
    rows = []
    for n in sizes:
        data = list(range(n))
        t0 = time.perf_counter(); fn(data); t = time.perf_counter() - t0
        rows.append((n, t, None if prev is None else t / prev))
        prev = t
    return rows

if __name__ == "__main__":
    print("== Operation counts ==")
    for n in (8, 16, 32, 64):
        a = list(range(n))
        cs = [OpCounter() for _ in range(5)]
        get_first(a, cs[0]); find_max(a, cs[1]); binary_search(a, -1, cs[2])
        merge_sort(a[::-1], cs[3]); has_duplicate_quadratic(a, cs[4])
        print(f"n={n:>3}  O(1)={cs[0].ops}  O(log n)={cs[2].ops}  O(n)={cs[1].ops}"
              f"  O(n log n)={cs[3].ops}  O(n^2)={cs[4].ops}")
    print("\n== Fibonacci calls ==")
    for n in (10, 20, 25):
        c1, c2 = OpCounter(), OpCounter()
        r1 = fib_naive(n, c1); r2 = fib_memo(n, c2)
        print(f"fib({n})={r1}  naive calls={c1.ops}  memo calls={c2.ops}  iter={fib_iter(n)}")
    print("\n== Duplicates ==")
    a = list(range(1000)); c1, c2 = OpCounter(), OpCounter()
    print(has_duplicate_quadratic(a, c1), c1.ops, has_duplicate_set(a, c2), c2.ops)
    print("\n== Recursion depth ==")
    print("limit:", sys.getrecursionlimit())
    print("sum_iterative(10**5):", sum_iterative(list(range(10**5))))
    try:
        sum_recursive(list(range(10**5)))
    except RecursionError as e:
        print("sum_recursive(10**5): RecursionError:", e)
    print("\n== Dynamic array ==")
    for n in (8, 16, 1000, 10**5):
        d = DynamicArray()
        for i in range(n): d.append(i)
        print(f"n={n:>6} copies={d.copies:>6}  (n+copies)/n = {(n + d.copies)/n:.3f}")
    print("\n== Peak memory (tracemalloc) ==")
    print("list(range(10**5)) bytes ~", peak_bytes(lambda: list(range(10**5))))
    print("sum generator  bytes ~", peak_bytes(lambda: sum(i for i in range(10**5))))
    print("\n== Doubling experiment: quadratic dup check ==")
    for n, t, r in doubling_experiment(lambda d: has_duplicate_quadratic(d, OpCounter()), [500, 1000, 2000]):
        print(f"n={n:>5} t={t:.4f}s ratio={r if r is None else round(r,2)}")

JReal-world applications

Complexity is not an exam topic that disappears after graduation; it is how engineers reason about whether a system will survive growth. Princeton's course names the primary practical reason for analysis bluntly: avoiding performance bugs, where a client gets poor performance because a programmer did not understand performance characteristics [6].

Figure J.1 · Real-world applicationDatabase lookup: full table scan vs index
table rows / index nodesrows or nodes inspectedrow foundindex pointerswasted reads
Without index: scan id=17 …id=3 …id=88 …id=41 …id=9 …id=52 ← targetid=26 … readrowby row O(n) rows touched in the worst case With a balanced index 30 | 703 | 1741 | 5288 | 954152 ✓ one node per level → O(log n) node visits
  1. Without an index the database must inspect rows until it finds id = 52 — every row in the worst case (red = wasted reads).
  2. A balanced search tree keyed on id compares against one node per level, so the path length is the tree height (orange path).
  3. Height of a balanced tree with branching factor ≥ 2 is O(log n).
Technical interpretation: B-trees keep height O(log n) while storing many keys per node, which is why they underlie disk-based indexes [1]. Illustration The node contents are invented for the drawing.
DomainWhere complexity decides the outcome
Backend engineeringIllustration A request handler that checks each of n incoming IDs with id in allowed_list is O(n·m); converting allowed_list to a set makes it O(n + m) on average [9]. The "N + 1 queries" anti-pattern (one query per row instead of one batched query) is the same mistake at the network level: cost grows linearly in round trips.
DatabasesIndexed lookups follow a balanced tree (O(log n)) instead of scanning (O(n)) — Figure J.1 [1]. Sorting-based operations such as ORDER BY or merge joins inherit the Ω(n log n) comparison-sorting lower bound unless an index already provides order [1].
Operating systems & runtimesCall stacks are finite. CPython's recursion limit exists to stop runaway recursion from overflowing the C stack and crashing the interpreter [11], so an algorithm's O(depth) stack space is an operational constraint, not just a theoretical one.
Networking & securityHash tables are O(1) only on average; when every key collides, operations become O(n) [9]. Attackers exploited this against web frameworks with crafted keys; Python responded by adding PYTHONHASHSEED hash randomization to protect against denial-of-service from worst-case dict behaviour [21].
Distributed systemsIllustration Any "every node talks to every node" protocol sends Θ(n²) messages per round; at 10 nodes that is 90 messages, at 1,000 nodes nearly a million — which is why large clusters prefer designs whose per-round cost is linear or logarithmic in cluster size.
Search enginesIllustration Search is dominated by sorted structures: binary search and merging of sorted lists are O(log n) and O(n + m) respectively [1], which is what makes querying web-scale collections feasible without scanning every document.
Web applicationsFront-end lists that re-filter all n items on every keystroke are O(n) per keystroke; adding a nested lookup inside the filter silently makes it O(n²). Profiling plus complexity reasoning finds these quickly.
Large-scale softwareCapacity planning uses the doubling hypothesis: measure at n and 2n, infer the exponent from the ratio, and predict cost at 10n before it ships [5][6].

KComparison with alternative approaches

K.1 Ways to judge an algorithm's cost

ApproachWhat it givesStrengthWeaknessUse when
Asymptotic analysis (O/Ω/Θ)growth classmachine-independent, predicts scaling [3]hides constants and small-n behaviour [14]choosing an algorithm / data structure
Tilde / exact countingleading term with constant, e.g. ∼ n³/6compares algorithms in the same class [5]more work to derivetuning two Θ(n log n) options
Empirical benchmarkingseconds on real hardwareincludes caches, interpreter, constants [5]machine-specific; can't extrapolate safelyfinal selection, regressions
Doubling experimentsempirical exponent b in T ∼ c·nbbridges theory and measurement [5]needs large enough nchecking a hypothesis about growth
Amortized analysiscost per operation over a sequencetight bounds for resizing structures [7]single operations can still be slowthroughput-oriented workloads
Average / expected analysiscost under an input distribution or random choicesrealistic for hashing, quicksort [1]adversarial inputs can break itinputs are random or randomized

K.2 Three solutions to one problem: "does the list contain a duplicate?"

SolutionTimeAux. spaceModifies input?Choose it when…
All pairsΘ(n²) worstΘ(1)non is tiny or memory is extremely tight
Sort, then compare neighboursO(n log n)O(1)–O(n) (in-place vs sorted() copy)yes, if sorted in placeitems are orderable but not hashable, or memory is limited
Hash setO(n) average, O(n²) worstO(n)nodefault choice for hashable items [9]
When to avoid "just pick the lowest Big-O" For small inputs, an O(n²) routine with tiny constants can beat an O(n log n) one; for adversarial inputs, average-case O(1) hashing can degrade to O(n) [9]; and an algorithm that is asymptotically faster but needs Θ(n) extra memory may be the wrong choice on an embedded device. Asymptotics narrows the shortlist — measurements and constraints decide.

LCommon mistakes and misconceptions

L.1 Hidden linear work inside a loop

✗ Looks O(n), is O(n·m)
result = []
for x in items:            # n times
    if x in banned_list:   # O(m) scan!
        result.append(x)
✓ O(n + m) average
banned = set(banned_list)    # O(m) once
result = [x for x in items
          if x in banned]      # O(1) avg

x in list is O(n), x in set is O(1) on average [9].

L.2 Using a list as a queue

✗ O(n) per dequeue
queue = [start]
while queue:
    node = queue.pop(0)  # shifts all
✓ O(1) per dequeue
from collections import deque
queue = deque([start])
while queue:
    node = queue.popleft()

list.pop(k) costs O(n − k), so pop(0) is O(n) [9]; deque.popleft() is O(1) [12]. Over a BFS of n nodes this is the difference between O(n²) and O(n).

L.3 Slicing in recursion

✗ "Binary search" that is O(n)
def bs(a, t):
    if not a: return False
    m = len(a) // 2
    if a[m] == t: return True
    return bs(a[m+1:], t) if a[m] < t \
        else bs(a[:m], t)   # copies!
✓ O(log n): pass indices
def bs(a, t, lo=0, hi=None):
    hi = len(a) - 1 if hi is None else hi
    if lo > hi: return False
    m = (lo + hi) // 2
    if a[m] == t: return True
    return bs(a, t, m+1, hi) if a[m] < t \
        else bs(a, t, lo, m-1)

A slice a[i:j] costs O(j − i) [9], so the left version copies n/2 + n/4 + … ≈ n elements: Θ(n) time and Θ(n) extra memory, despite doing only O(log n) comparisons.

L.4 Complexity misconceptions

MisconceptionCorrection
"Big-O means worst case."O is an upper bound on a function; worst/best/average choose the function. You can give an O bound on the best case [1].
"O(n) means exactly proportional to n."O is only an upper bound; 3n + 4 is O(n²) too. Use Θ when you mean "exactly this order". NIST's dictionary notes Big-O is often misused to mean "equal to" [15].
"Two nested loops ⇒ O(n²)."Only if both run Θ(n) times. An inner halving loop gives O(n log n); a two-pointer inner loop whose pointer never resets gives O(n) total.
"O(n/2) is better than O(n)."Constants are dropped: O(n/2) = O(n) [4].
"Dict lookups are always O(1)."Average O(1); worst case O(n) when keys collide [9].
"Recursion uses no extra memory."Each active call holds a stack frame: depth d ⇒ Θ(d) space (Figure F.1).
"Amortized O(1) means every call is fast."Individual appends can be O(n); only the sequence average is bounded [9][7].
"With two inputs, write O(n)."Keep both variables: merging lists of sizes n and m is O(n + m); a grid is O(rows·cols).

L.5 Boundary-condition and interview mistakes

MInterview preparation

M.1 Questions interviewers actually ask

  1. What is the time and space complexity of your solution? Can you do better?
  2. What is the difference between O, Ω and Θ? Between worst-case and amortized?
  3. Why is list.append O(1) if the list sometimes resizes?
  4. What is the space complexity of a recursive DFS on a path-shaped tree of n nodes?
  5. Your hash-map solution is O(n) — when could it be O(n²)?

M.2 Pattern: read the constraints, infer the target complexity

Illustration A widely used rule of thumb, assuming roughly 10⁸ simple operations per second and a 1-second limit (a pure-Python solution manages far fewer, so aim one row lower):

n up toFeasible complexityTypical technique
10–12O(n!)permutations, brute force
20–25O(2ⁿ), O(n·2ⁿ)subsets, bitmask DP
≈ 500O(n³)triple loops, Floyd–Warshall
≈ 5,000O(n²)2-D DP, all pairs
10⁵ – 10⁶O(n log n)sorting, heaps, binary search
10⁷ – 10⁸O(n)one pass, two pointers, hashing
> 10⁹O(log n) or O(1)math, binary search on the answer

M.3 Practice problems

Easy · LeetCode 217 — Contains Duplicate Easy

Return True if any value appears at least twice.

HintCompare the three approaches in K.2. Which one is O(n)?
Optimized approach & complexity
def contains_duplicate(nums):
    seen = set()
    for x in nums:
        if x in seen:
            return True
        seen.add(x)
    return False
O(n) average time, O(n) space. Brute force is Θ(n²)/Θ(1); sorting is O(n log n).

Easy · LeetCode 1 — Two Sum Easy

Return indices of two numbers that add up to target.

HintFor each x, the partner you need is target − x. Can you check for it in O(1)?
Optimized approach & complexity
def two_sum(nums, target):
    index_of = {}
    for i, x in enumerate(nums):
        if target - x in index_of:
            return [index_of[target - x], i]
        index_of[x] = i
    return []
O(n) average time, O(n) space, versus Θ(n²) for checking all pairs.

Medium · LeetCode 53 — Maximum Subarray Medium

Find the contiguous subarray with the largest sum.

Hint 1Brute force over all (i, j) pairs is O(n²) with running sums, O(n³) without.
Hint 2The best subarray ending at i either extends the best one ending at i − 1 or starts fresh at i.
Optimized approach & complexity (Kadane)
def max_subarray(nums):
    best = cur = nums[0]
    for x in nums[1:]:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best
Θ(n) time. Note nums[1:] copies: Θ(n) extra space; iterate with indices for Θ(1). A divide-and-conquer version satisfies T(n) = 2T(n/2) + Θ(n) ⇒ Θ(n log n).

Medium · LeetCode 3 — Longest Substring Without Repeating Characters Medium

HintKeep a window [left, right]. Each pointer only moves forward. How many total moves is that?
Optimized approach & complexity
def length_of_longest_substring(s):
    last = {}
    left = best = 0
    for right, ch in enumerate(s):
        if ch in last and last[ch] >= left:
            left = last[ch] + 1
        last[ch] = right
        best = max(best, right - left + 1)
    return best
O(n) time: right moves n times and left only jumps forward. Space O(min(n, k)) for alphabet size k. This is the "nested-looking but linear" pattern from L.4.

Hard · LeetCode 4 — Median of Two Sorted Arrays Hard

The required runtime is O(log(m + n)).

Hint 1Merging is O(m + n). The log requirement means you must binary-search something.
Hint 2Binary-search a cut position i in the shorter array; the cut j in the other array is then forced so that the left halves have (m + n + 1) // 2 elements.
Optimized approach & complexity
def find_median_sorted_arrays(A, B):
    if len(A) > len(B):
        A, B = B, A
    m, n = len(A), len(B)
    half = (m + n + 1) // 2
    lo, hi = 0, m
    INF = float("inf")
    while lo <= hi:
        i = (lo + hi) // 2
        j = half - i
        a_left  = A[i - 1] if i > 0 else -INF
        a_right = A[i]     if i < m else INF
        b_left  = B[j - 1] if j > 0 else -INF
        b_right = B[j]     if j < n else INF
        if a_left <= b_right and b_left <= a_right:
            if (m + n) % 2:
                return max(a_left, b_left)
            return (max(a_left, b_left) + min(a_right, b_right)) / 2
        if a_left > b_right:
            hi = i - 1
        else:
            lo = i + 1
O(log min(m, n)) time, O(1) space — the search runs only over the shorter array.

M.4 Self-check: what is the complexity?

Lab 7 · Quick quizName the tight bound
Answer each card; feedback appears immediately.

NAdvanced concepts

N.1 The potential method

The most general amortization technique assigns a potential Φ to the data structure's state and defines amortized cost = actual cost + Φ(after) − Φ(before); summing telescopes to actual total + Φ(final) − Φ(initial), so any Φ that starts at 0 and stays non-negative yields valid bounds [7][18]. For a doubling table, Φ = 2·size − capacity works: cheap inserts raise Φ by 2, and a resize's Θ(n) copying is paid for by the drop in Φ.

N.2 Expected time of randomized algorithms

Randomized quicksort runs in expected O(n log n) on every input, because the randomness lives in the algorithm, not the data; its worst case remains Θ(n²) [1]. This differs from average-case analysis, which assumes a distribution over inputs.

N.3 Lower bounds: proving you can't do better

Any comparison-based sorting algorithm needs Ω(n log n) comparisons in the worst case, by the decision-tree argument: there are n! possible orderings, a binary decision tree with n! leaves has height ≥ log₂(n!) = Θ(n log n) [1]. So merge sort is asymptotically optimal among comparison sorts; beating n log n requires extra assumptions (e.g. integer keys for counting or radix sort) [1].

N.4 Input size in bits and pseudo-polynomial time

Complexity is measured in the size of the input. A loop for d in range(2, N) that tests whether N is prime is O(N) — linear in the value, but the input is only b ≈ log₂ N bits long, so it is O(2b): exponential in the input size. Algorithms polynomial in a numeric value but not in its bit length are called pseudo-polynomial (the classic 0/1-knapsack DP is O(n·W)). MIT 6.006 defines efficiency as polynomial time with respect to the input size [2].

N.5 Multi-parameter and output-sensitive bounds

Graph algorithms are stated in V and E (BFS/DFS: O(V + E)) [1]; string matching in text length and pattern length; and output-sensitive algorithms include the output size k, e.g. reporting all k points in a range. Collapsing these into one "n" loses information.

N.6 Beyond the RAM model

The word-RAM charges every memory access the same O(1) [2], but real hardware has caches and disks where locality dominates. External-memory models count block transfers instead — another reason B-trees use wide nodes. MIT's performance-engineering course (6.172) builds on the same divide-and-conquer recurrences used here [8].

ONotebook-ready summary

First, the whole idea on one page — copy this sheet into your notebook. The detailed revision notes follow it.

Time & Space Complexity
How the running time and memory of an algorithm grow with input size (n)
What is Time Complexity?

A way to measure how the number of steps an algorithm takes grows as the input size n grows. We count steps, not seconds.

What is Space Complexity?

How the extra memory it needs grows with n: variables, copies, and the call stack for recursion.

Big-O Notation
An upper bound on growth (usually the worst case). Drop constant factors and lower-order terms.

Example:  3n + 5 → O(n)

O = ceiling · Ω = floor · Θ = both (tight)

Why it matters?
  • Compare different solutions.
  • Predict how code scales on big inputs.
  • Choose the most efficient approach.
Common Time Complexities
Big-ONameTypical example
O(1)Constantarray index, hash lookup
O(log n)Logarithmicbinary search
O(n)Linearone loop over n items
O(n log n)Linearithmicmerge sort, heap sort
O(n²)Quadraticnested loops (n × n)
O(n³)Cubicthree nested loops
O(2ⁿ)Exponentialall subsets
O(n!)Factorialall orderings
Growth Comparison
Order: Fast → Slow
O(1) < O(log n) < O(n) < O(n log n)
< O(n²) < O(n³) < O(2ⁿ) < O(n!)
Examples
O(1) · Constant
def get_first(arr):
    return arr[0]
Steps: 1 → O(1)
10arr[0]
20
30
O(n) · Linear
def sum_array(arr):
    total = 0
    for x in arr:
        total += x
    return total
Steps: ≈ n → O(n)
10
20
30
…
n
O(n²) · Quadratic
def print_pairs(arr):
    for a in arr:
        for b in arr:
            print(a, b)
Steps: n × n → O(n²)
O(log n) · Logarithmic
def binary_search(arr, x):
    lo, hi = 0, len(arr) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        ...  # keep one half
Steps: ≈ log₂ n → O(log n)
10lo
20
30mid
40
50hi
Space: quick rules
  • A few variables → O(1) extra space.
  • A new list / dict of n items → O(n).
  • Recursion depth d → O(d) stack space.
  • Slicing arr[a:b] makes a copy.
★ Key Takeaways
  • Complexity = how cost grows with n.
  • Keep the dominant term: 3n² + 5n → O(n²).
  • Lower growth = more efficient for large n.
  • Always state time and space.

Detailed revision notes

1 · Definitions

Time complexity T(n) = # primitive steps on input of size n (usually worst case).
Space complexity S(n) = peak extra memory (variables + copies + call stack).
f = O(g) ⟺ ∃ c>0, n₀: f(n) ≤ c·g(n) ∀ n ≥ n₀  (upper bound)
f = Ω(g) ⟺ ∃ c>0, n₀: f(n) ≥ c·g(n) ∀ n ≥ n₀  (lower bound)
f = Θ(g) ⟺ both  (tight: c₁g ≤ f ≤ c₂g)
Limit test: f/g → 0 ⇒ o(g); → const > 0 ⇒ Θ(g); → ∞ ⇒ ω(g)

2 · Core idea

Drop constants & lower terms → keep the growth shape. 3n² + 5n + 2 = Θ(n²).
1 ≺ log n ≺ √n ≺ n ≺ n log n ≺ n² ≺ n³ ≺ 2ⁿ ≺ n!

3 · Loop rules

single loop → n  ·  nested (n×n) → n²  ·  j from i+1 → n(n−1)/2 = Θ(n²)
i //= 2 → log n  ·  loop × halving → n log n  ·  sequential blocks → max, nested → multiply

4 · Recurrences

T(n/2)+1 → log n · T(n−1)+1 → n · 2T(n/2)+n → n log n · 2T(n−1)+1 → 2ⁿ
Master: aT(n/b)+f(n) — compare f with n^(log_b a): smaller → leaves win, equal → ×log n, bigger → f wins

5 · Python costs

list: a[i] O(1) · append O(1)* · pop() O(1) · pop(0)/insert(0) O(n) · x in list O(n) · slice O(k) · sort O(n log n)
dict/set: get/set/in O(1) avg, O(n) worst · deque: both ends O(1)   (*amortized)

6 · Space

recursion depth d ⇒ Θ(d) stack · default recursion limit 1000 · slicing copies · generator ≈ O(1)

7 · Amortized

grow by ×factor ⇒ total copies < 2n ⇒ O(1) per append · grow by +const ⇒ Θ(n²) total

8 · Interview takeaways

① define n (and m, V, E) ② state time AND space ③ say best/avg/worst/amortized ④ look for hidden O(n) inside loops ⑤ use constraints to guess the target class ⑥ hashing is avg O(1), not guaranteed
Figure O.1 · Notebook sketchOne picture to remember
Ω — floorO — ceilingf(n)n₀Θ = both
c₂·g(n) — O: never above (after n₀) f(n) c₁·g(n) — Ω: never below n₀ Θ: trapped
Technical interpretation: O is a ceiling, Ω a floor, Θ both — each only required to the right of n₀ [1][4].

PKnowledge assessment

Attempt everything before opening the answer key in P.5.

P.1 Conceptual questions

  1. Is n² = O(n³)? Is n² = Θ(n³)? Justify each with the definitions.
  2. Explain why O(log₂ n) and O(log₁₀ n) are the same class but O(2ⁿ) and O(3ⁿ) are not.
  3. Give an operation whose worst-case cost is O(n) but whose amortized cost is O(1), and explain why the two statements don't contradict each other.
  4. A recursive function makes 2 calls per invocation and has depth n. Why is its time exponential while its space is only linear?
  5. Your colleague says "our hash-map solution is O(1) per lookup, so it can never be slow." Give two reasons this is incomplete.

P.2 Dry-run exercises

  1. Count exactly how many times work() runs, then give Θ:
    for i in range(n):
        j = 1
        while j < n:
            work()
            j *= 2
    for n = 8 and n = 10.
  2. Trace binary_search([2, 4, 6, 8, 10, 12, 14], 4): give lo, hi, mid, a[mid] and the decision for each iteration.
  3. Starting from capacity 1 and doubling, how many element copies occur while appending 17 items? What is the total cost (writes + copies) and the cost per append?

P.3 Coding problems

  1. Pair with difference k. Given a list of distinct integers and k > 0, return whether two elements differ by exactly k. Write an O(n²) version and an O(n) average version; state their space costs.
  2. Fix the queue. Rewrite this level-order traversal so it runs in O(n) instead of O(n²):
    def levels(root):
        q, out = [root], []
        while q:
            node = q.pop(0)
            out.append(node.val)
            q.extend(c for c in (node.left, node.right) if c)
        return out
  3. Measure it. Write estimate_exponent(fn, n) that times fn on inputs of size n and 2n (repeat 5 times, take the minimum) and returns log₂ of the ratio. Use it to check that sorted() on random data gives roughly 1 and an all-pairs loop gives roughly 2.

P.4 Practical engineering scenario

An internal "find similar customers" endpoint compares every customer against every other customer using a 50-field similarity score. It took 0.4 s when the company had 2,000 customers; there are now 40,000 and growing 10% per month. Product asks whether a bigger server will fix it. Estimate the current runtime, explain what scaling hardware can and cannot do, and propose a redesign with its complexity.

P.5 Answer key

Conceptual answers
  1. Yes: n² ≤ 1·n³ for n ≥ 1 (c = 1, n₀ = 1). No: Θ would need n² ≥ c·n³, i.e. n ≤ 1/c for all large n — impossible. So n² = O(n³) but n² = o(n³), not Θ.
  2. log₂ n = log₁₀ n / log₁₀ 2, a constant factor, which O absorbs. But 3ⁿ / 2ⁿ = (1.5)ⁿ → ∞, so no constant c makes 3ⁿ ≤ c·2ⁿ: different classes.
  3. list.append: a single call that triggers a resize copies all n elements (O(n)), but over any sequence of k appends the total is O(k) [9][7]. Worst-case bounds a single operation; amortized bounds the average over a sequence — both are true.
  4. Time counts all nodes of the recursion tree (up to 2ⁿ). Space counts only frames alive simultaneously — a single root-to-leaf path of length n — because a call's frame is freed when it returns (Lab 4).
  5. (a) O(1) is average; adversarial or poorly-distributed keys make lookups O(n) [9][21]. (b) O hides constants — hashing large keys or a lookup inside an O(n) loop still costs O(n) per request; plus memory is O(n).
Dry-run answers
  1. The inner loop runs for j = 1, 2, 4, … while j < n, i.e. ⌈log₂ n⌉ times. n = 8: 8 × 3 = 24 calls. n = 10: 10 × 4 = 40 calls. Θ(n log n).
  2. Iterlohimida[mid]Decision
    106388 > 4 → hi = 2
    20214found → return 1
  3. Resizes happen at appends 2, 3, 5, 9, 17 copying 1 + 2 + 4 + 8 + 16 = 31 elements. Total cost = 17 writes + 31 copies = 48; 48 / 17 ≈ 2.82 < 3.
Coding answers
import math, random, time
from collections import deque

# 1. Pair with difference k
def has_pair_diff_slow(nums, k):        # Θ(n²) time, Θ(1) space
    n = len(nums)
    return any(abs(nums[i] - nums[j]) == k
               for i in range(n) for j in range(i + 1, n))

def has_pair_diff_fast(nums, k):        # O(n) average time, O(n) space
    s = set(nums)
    return any(x + k in s for x in nums)

# 2. Level order with a deque: O(n) time, O(width) queue space
def levels(root):
    if root is None:
        return []
    q, out = deque([root]), []
    while q:
        node = q.popleft()
        out.append(node.val)
        q.extend(c for c in (node.left, node.right) if c)
    return out

# 3. Empirical exponent via the doubling hypothesis
def estimate_exponent(fn, n, repeats=5):
    def best_time(size):
        data = [random.random() for _ in range(size)]
        best = float("inf")
        for _ in range(repeats):
            t0 = time.perf_counter(); fn(data); best = min(best, time.perf_counter() - t0)
        return best
    return math.log2(best_time(2 * n) / best_time(n))

def all_pairs(a):
    c = 0
    for i in range(len(a)):
        for j in range(i + 1, len(a)):
            c += 1
    return c

print(round(estimate_exponent(sorted, 200_000), 2))    # ≈ 1 (n log n looks ~1.0–1.1)
print(round(estimate_exponent(all_pairs, 1_500), 2))  # ≈ 2

On our run, estimate_exponent(sorted, 200_000) printed 1.11 and estimate_exponent(all_pairs, 1_500) printed 2.0 — consistent with n log n (slightly above 1) and n². Your numbers will vary slightly.

Engineering scenario — model answer

Diagnose. All-pairs comparison is Θ(n²) (n(n−1)/2 pairs × 50 fields). Going from 2,000 to 40,000 customers multiplies n by 20, so time grows by ≈ 20² = 400: 0.4 s × 400 ≈ 160 s per request. With 10% monthly growth, n doubles roughly every 7.3 months, quadrupling the time each doubling [5].

Hardware. A 4× faster server buys exactly one doubling of n — about 7 months — after which the problem returns. Faster machines change the constant, not the class.

Redesign. (1) Answer per-customer queries instead of recomputing all pairs: compare one customer against n others, O(n) per request. (2) Precompute offline in batch jobs, cache results, and refresh incrementally. (3) Index by blocking keys (region, segment) or use approximate nearest-neighbour indexing so each query inspects a small candidate set rather than all n. (4) Measure with a doubling experiment after each change to confirm the new exponent.

QReferences and further reading

  1. T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022. Asymptotic notation (Ch. 3), cost-times analysis, best/worst/average case, recurrences and master method (Ch. 4), randomized quicksort, sorting lower bound, B-trees, BFS/DFS bounds (Sections B, F, G, H, J, K, N).
  2. MIT OpenCourseWare, 6.006 Introduction to Algorithms (Spring 2020), Lecture 1: Introduction (E. Demaine, J. Ku, J. Solomon). Efficiency as polynomial time, counting fixed-time operations, word-RAM model and w ≥ log n, growth table at n = 1000 (Sections B, D, F, N).
  3. MIT OpenCourseWare, 6.006 (Fall 2011), Recitation 1: Asymptotic Complexity. Purpose of asymptotic notation, misleading "=" in Θ(x²), hidden constants (Sections B, C, G, K).
  4. Stanford University, CS 161 (Winter 2023), Lecture 2: MergeSort, Recurrences 101, and Asymptotic Analysis (adapted from V. Williams; N. Anari, M. Charikar). Formal O/Ω/Θ definitions, merge-sort recursion tree, worst-case-as-adversary rationale (Sections B, G, H, L, O).
  5. R. Sedgewick, K. Wayne, "4.1 Analysis of Algorithms," Computer Science: An Interdisciplinary Approach, Princeton University. Tilde notation, order of growth, inner-loop counting, ThreeSum n(n−1)(n−2)/6, doubling hypothesis (Sections B, C, F, I, J, K, P).
  6. R. Sedgewick, K. Wayne, COS 226 lecture slides "1.4 Analysis of Algorithms", Princeton University, Fall 2019. Reasons to analyze algorithms, avoiding performance bugs, N-body example, order-of-growth classifications (Sections B, D, J).
  7. MIT OpenCourseWare, 6.046J Design and Analysis of Algorithms (Spring 2015), Lecture 5: Amortization. Amortized cost definition, aggregate/accounting/potential methods, table doubling (Sections B, G, H, K, L, N, P).
  8. C. E. Leiserson et al., MIT 6.172 Performance Engineering of Software Systems, "Divide-and-Conquer Recurrences" review slides. Master method for T(n) = aT(n/b) + f(n), recursion-tree derivation (Sections G, N).
  9. Python Software Foundation, "Time complexity of operations on built-in types", Python 3 documentation. Costs for list/dict/set, amortized append note, dict worst case O(n), adaptive O(n log n) sort, slicing costs (Sections F, H, I, J, K, L, P).
  10. Python Wiki, "TimeComplexity". CPython list represented internally as an array; other implementations may differ (Sections F, H).
  11. Python Software Foundation, sys.setrecursionlimit / getrecursionlimit, Python 3 documentation. Recursion limit and its purpose of preventing C-stack overflow (Sections F, I, J).
  12. Python Software Foundation, collections.deque, Python 3 documentation. O(1) appends and pops at both ends (Sections H, I, L).
  13. D. E. Knuth, "Big Omicron and Big Omega and Big Theta," ACM SIGACT News 8(2):18–24, 1976. History of O (Bachmann 1894, Landau), proposal of Ω and Θ for computer science (Sections B, G).
  14. E. Lehman, F. T. Leighton, A. R. Meyer, Mathematics for Computer Science, §13.7 "Asymptotic Notation", MIT OpenCourseWare 6.042J. Big O as the most-used upper bound, Θ and scalability, pitfalls with asymptotic notation (Sections G, H, K).
  15. P. E. Black (ed.), "big-O notation," Dictionary of Algorithms and Data Structures, NIST. Informal definition and note that Big-O is often misused to mean "equal to" (Section L).
  16. A. Tomescu, "'Big Oh' notation in terms of limits," MIT 6.006 Recitation 1, Spring 2014. Limit characterizations of o, O, Θ, Ω, ω (Section G).
  17. Python Software Foundation, timeit — Measure execution time of small code snippets. Timing methodology and repeated measurements (Sections I, L).
  18. MIT OpenCourseWare, 6.046J (Spring 2012), Lecture 11: Amortized Analysis. Second source for aggregate, accounting and potential methods (Sections H, N).
  19. F. Lundh, quoting CPython listobject.c, "Looking for info on Python's memory allocation," python-list, 2005. CPython list over-allocates proportionally to size, giving linear-time amortized appends (Section H).
  20. Python Software Foundation, tracemalloc — Trace memory allocations. Measuring current and peak traced memory (Section I).
  21. python-dev mailing list, "Issue #13703: oCERT-2011-003: add -R command-line option and PYTHONHASHSEED", 2012. Hash randomization added to protect against denial of service via worst-case dict behaviour (Sections J, P).
  22. Python Software Foundation, bisect — Array bisection algorithm. Built-in binary search on sorted lists (Section I).
  23. Python Software Foundation, functools.lru_cache / cache. Built-in memoization trading memory for time (Section I).

Practice problem sources

LeetCode problems 1, 3, 4, 53 and 217 are linked at their point of use in Section M. Problem statements are owned by their respective sites.