Big-O Complexity
Time and space complexity of the data structures and algorithms you use every day.
Big-O describes how an algorithm’s running time or memory grows as the input grows, ignoring constant factors and machine speed. O(n) means doubling the input roughly doubles the work; O(n²) means it roughly quadruples. It answers “will this still work with 100× the data?”, not “how many milliseconds?”.
Unless a row says otherwise, figures are average-case time and n is the number of elements; worst cases are called out where they differ. Constants and memory access patterns still matter in real systems — measure once Big-O has ruled out the hopeless options.
n log n has reached 160 operations, n² left the chart at n ≈ 12.6 and 2ⁿ at n ≈ 7.3, while log n is still at 5.Growth rates (best → worst)
- O(1)
- Constant — hash lookup, array index
- O(α(n))
- inverse Ackermann — union-find with path compression; below 5 for any real n
- O(log n)
- Logarithmic — binary search, balanced tree
- O(√n)
- square root — trial-division primality, sqrt decomposition
- O(n)
- Linear — scan a list
- O(n log n)
- Linearithmic — good sorts (merge, heap, quick avg)
- O(n²)
- Quadratic — nested loops, bubble sort
- O(n³)
- cubic — naive matrix multiplication, Floyd–Warshall
- O(2ⁿ)
- Exponential — subsets, naive recursion
- O(n!)
- Factorial — permutations, brute-force TSP
Data structures (average)
- Array — access
O(1)· searchO(n)· insert/deleteO(n)- Hash map
- search / insert / delete
O(1) - Balanced BST
- search / insert / delete
O(log n) - Heap
- peek
O(1)· push / popO(log n) - Stack / Queue
- push / pop
O(1) - Linked list
- access
O(n)· insert at headO(1) - Dynamic array append
O(1)amortized; an occasional resize copies everything inO(n)- Deque
- push / pop at both ends
O(1)— the right queue in Python - Trie
- insert / search
O(L)for a key of length L, independent of how many keys - Union-find
- union / find
O(α(n))amortized with path compression and union by rank - LRU cache
- get / put
O(1)— a hash map plus a doubly linked list
Worst cases & amortized
- Worst case
- the slowest input of size n — the guarantee you can rely on
- Average case
- expected cost over random inputs, or random choices such as pivots
- Amortized
- average per operation over a sequence — rare expensive steps paid for by many cheap ones
- Hash map, worst
O(n)when every key collides — bad hash functions or adversarial input- Unbalanced BST, worst
O(n): inserting sorted keys builds a linked list — why balanced trees exist
Python & JavaScript built-ins
- list.append / list.pop()
O(1)amortized at the end of the list- list.insert(0, x) / pop(0)
O(n)— every element shifts; usecollections.deque- x in list
O(n)scan;x in setandx in dictareO(1)average- sorted() / list.sort()
O(n log n)Timsort, stable; close toO(n)on already-sorted data- heapq.heappush / heappop
O(log n);heapifybuilds a heap from a list inO(n)- a[i:j]
O(j − i): slicing copies — not free inside a loop- s += "x" in a loop
- can be
O(n²)in total — collect pieces in a list, then"".join() - arr.push / arr.pop (JS)
O(1)amortized;shiftandunshiftareO(n)- arr.includes (JS)
O(n);Set.hasandMap.getareO(1)average
Sorting
- Quicksort
- avg
O(n log n)· worstO(n²)· in-place - Merge sort
O(n log n)always ·O(n)space · stable- Heap sort
O(n log n)· in-place · not stable- Counting / radix
- counting
O(n + k)· radixO(d·(n + b))— non-comparison, bounded keys - Insertion sort
O(n²), butO(n)on nearly sorted input — used inside Timsort for small runs- Timsort
O(n log n)worst,O(n)best, stable — Python and Java’s object sort- Bubble / selection
O(n²)— teaching tools, never the right production choice- Comparison lower bound
- any comparison sort needs
Ω(n log n)comparisons in the worst case
Analysis rules
- Drop constants
O(2n)isO(n)— Big-O tracks growth, not exact cost- Keep the dominant term
O(n² + n)isO(n²)- Sequential vs nested
- loops one after another add:
O(n + m); a loop inside a loop multiplies:O(n·m) - Halving every step
O(log n)— binary search, balanced-tree height- Recursion uses space
- call-stack depth counts: recursive DFS needs
O(depth)extra memory - T(n) = 2T(n/2) + O(n)
O(n log n)— merge sort, by the master theorem- T(n) = T(n/2) + O(1)
O(log n)— binary search- T(n) = 2T(n − 1) + O(1)
O(2ⁿ)— recursion that branches twice and shrinks by one- O / Ω / Θ
- upper / lower / tight bound — interviews say O but usually mean Θ
Input size → what will pass
- n ≤ 10
O(n!)— try every permutation- n ≤ 20
O(2ⁿ)— every subset, bitmask DP- n ≤ 500
O(n³)— triple loops, Floyd–Warshall- n ≤ 5,000
O(n²)— all pairs, 2-D DP tables- n ≤ 10⁶
O(n log n)— sort, heap, binary search- n ≤ 10⁸
O(n)— single pass; beyond that,O(log n)or a formula
Worked example: find the hidden quadratic by doubling n
A dedupe step is slow, and nobody knows why. Do not guess: time it at n, 2n and 4n and look at the ratio. Linear code doubles; quadratic code quadruples. The two versions below differ in one word.
def dedupe_list(xs):
seen, out = [], []
for x in xs:
if x not in seen: # O(n) scan of a list
seen.append(x); out.append(x)
return out
def dedupe_set(xs): # same code, seen = set()
... # x not in seen is O(1) average
Measured with time.perf_counter() on random integers, Python 3, one laptop:
n= 5,000 list 51.5 ms set 0.32 ms
n= 10,000 list 191.3 ms set 0.71 ms
n= 20,000 list 746.5 ms set 1.15 ms
- Each doubling of n multiplies the list version by 3.7–3.9, close to 4: the signature of
O(n²). The set version roughly doubles:O(n). - Extrapolate before it bites: at n = 1,000,000 the list version needs (1,000,000 / 20,000)² = 2,500 times longer, about 31 minutes. The set version needs about 50 times longer, around 60 ms.
- The fix was not a cleverer algorithm. It was the right container for the operation done n times.
Your milliseconds will differ from these; the ratios will not. That is the whole promise of Big-O.
Recipes
Two-sum: from O(n²) to O(n) with a hash map
# Brute force: check every pair -> O(n^2) time, O(1) extra space
def two_sum_slow(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return i, j
# One pass with a dict -> O(n) time, O(n) extra space
def two_sum(nums, target):
seen = {} # value -> index
for i, x in enumerate(nums):
if target - x in seen: # O(1) average lookup
return seen[target - x], i
seen[x] = iThe classic time-for-space trade: n·(n−1)/2 pair checks become n dictionary lookups, at the cost of storing up to n entries.
Derive the complexity of a triangular nested loop
for i in range(n): # outer loop: n times
for j in range(i, n): # inner loop: n - i times
work() # O(1)
total calls = n + (n-1) + ... + 1 = n(n+1)/2
= 0.5n^2 + 0.5n
drop the constant and the lower term -> O(n^2)Starting the inner loop at i halves the work, but halving changes the constant, not the growth rate — the loop is still quadratic.
Why appending to a dynamic array is amortized O(1)
capacity grows geometrically, e.g. doubling: 1, 2, 4, 8, ..., n
copies made while growing to n: 1 + 2 + 4 + ... + n/2 < n
total work for n appends: n writes + fewer than n copies < 2n
work per append: under 2n / n = O(1) amortizedAny single append can still cost O(n) when it triggers a resize, so latency-sensitive code may see spikes; preallocate when you know the final size.
Pick an approach from the input size
n = 200,000 items, 1 second limit (about 10^8 simple operations)
O(n^2) = 4 * 10^10 operations -> far too slow
O(n log n) = 200,000 * 17.6 ≈ 3.5 * 10^6 -> fine
=> sort first, or use a heap, hash map or binary search; no nested loopsThe 10⁸-per-second budget fits C++ or Java; pure Python loops run far slower (often 10–100×), so an O(n log n) plan matters even more there.
Binary search: why log n is so small
n = 1,000,000 sorted items
each comparison halves the range: 1,000,000 -> 500,000 -> 250,000 -> ...
comparisons until one item is left: log2(1,000,000) ≈ 20
doubling n to 2,000,000 adds just one more comparisonThat is why sorting once (O(n log n)) and then searching many times (O(log n) each) beats scanning the list for every query.
When to use it, and when not
Reach for Big-O when choosing between approaches before writing them, when picking a data structure by its most frequent operation, when reviewing code that loops over growing data, and when checking whether a plan fits an input size and time limit.
Look past it when:
- n is small and fixed. Below a few dozen elements, constants win: Timsort switches to insertion sort for short runs for exactly this reason.
- Memory or I/O dominates. Count cache misses, disk reads or network round trips instead. A B-tree and a binary search tree are both
O(log n), but one costs a handful of disk reads and the other dozens. - Latency must be bounded. Use worst-case or amortized bounds explicitly; an average-case
O(1)can still spike. - The work runs in parallel. Total work and the longest chain of dependent steps are different numbers, and the second sets the wall-clock time.
Trade-offs and limits
| What Big-O hides | Example |
|---|---|
| Constant factors | a linked-list scan and an array scan are both O(n), but every list node is a pointer chase that may miss the cache |
| Lower-order terms | n² + 1000n is dominated by the 1000n term until n passes 1,000 |
| Memory hierarchy | for a billion keys, a binary tree is about 30 levels deep and a B-tree with 500-way nodes about 4 |
| Average versus worst | quicksort is O(n log n) on average and O(n²) on bad pivots |
| Amortized spikes | a dynamic-array append is O(1) amortized and O(n) on the resize |
Time and space also trade against each other: the two-sum recipe buys O(n) time with O(n) extra memory, and caching, memoization and precomputed indexes all make the same deal.
Common mistakes
- A hidden loop inside a built-in.
x in some_list,list.pop(0),arr.shift()and slicing are eachO(n). Inside a loop over n items they make the whole thing quadratic. - Measuring n by the value instead of the size. Trial division is
O(√N)in the number N, which is exponential in its digit count. The knapsack DP’sO(n·W)is pseudo-polynomial for the same reason. - Forgetting the cost of the key. Hashing or comparing a string of length L costs
O(L). Sorting n strings isO(n log n)comparisons, each of which may read up to L characters. - Sorting inside a loop. Re-sorting a list each time an item arrives costs
O(n log n)per item andO(n² log n)in total. A heap or a balanced tree keeps order inO(log n)per insert. - Collapsing two variables into one. BFS is
O(V + E), and E can reach V² in a dense graph. WritingO(n)hides the term that actually decides the running time.
Check yourself
What is the complexity of: for i in range(n): j = 1; while j < n: j *= 2?
The outer loop runs n times and the inner loop doubles j, so it runs about log₂ n times: O(n log n).
Solve T(n) = 3T(n/2) + O(n).
By the master theorem, log₂ 3 ≈ 1.585 > 1, so the recursion dominates: O(n^1.585). This is Karatsuba multiplication.
An O(n²) job takes 2 s at n = 10,000. Roughly how long at n = 50,000? And if it were O(n log n)?
Quadratic: (5)² = 25×, so about 50 s. Linearithmic: 5 × log(50,000)/log(10,000) ≈ 5 × 1.17 ≈ 5.9×, so about 12 s.
A Python BFS uses queue.pop(0) on a list. What is the cost over V vertices, and what fixes it?
Each pop(0) shifts the whole list, so dequeuing costs O(V²) in total. Use collections.deque and popleft(), which is O(1), to get back to O(V + E).
Questions about Big-O Complexity Cheat Sheet
What is Big-O notation?
Big-O notation describes an upper bound on how the running time or memory use of an algorithm grows as its input size n grows. It keeps only the fastest-growing term and drops constant factors, so 3n squared plus 5n plus 2 is written O(n squared). That makes it a tool for comparing approaches at scale rather than predicting exact speed: an O(n log n) algorithm will eventually beat an O(n squared) one as n grows, even if it is slower on tiny inputs. Time and space are analyzed separately, and you usually state the worst case unless you say otherwise.
What does amortized O(1) mean?
Amortized cost is the average cost per operation over a long sequence of operations, even when some individual operations are expensive. Appending to a dynamic array such as a Python list or a JavaScript array is the classic example. Most appends just write into spare capacity, but when the array is full it allocates a larger block and copies everything, which takes O(n). Because the capacity grows geometrically, those copies are rare enough that n appends take O(n) time in total, or O(1) each on average. Unlike average-case analysis, amortized analysis needs no assumptions about random input.
Is a hash map lookup really O(1)?
On average, yes. A hash map turns the key into an array index, so with a good hash function and a sensible load factor each bucket holds only a few entries and a lookup inspects a constant number of them. In the worst case, when many keys land in the same bucket, a lookup degrades to O(n), which attackers can exploit with crafted keys; many languages randomize their hash seeds for that reason. Resizing the table costs O(n) but happens rarely, so inserts stay O(1) amortized. Hashing itself also takes time proportional to the key length.
What is the difference between Big-O, Big-Omega and Big-Theta?
They are three kinds of bounds. Big-O is an upper bound: the function grows no faster than the given rate. Big-Omega is a lower bound: it grows at least that fast. Big-Theta is a tight bound, meaning both at once. Merge sort, for example, is Theta of n log n, because it always does that much work, while quicksort is O of n squared in the worst case and Theta of n log n on average. In everyday engineering and interviews, people say Big-O but usually mean the tight bound for the case being discussed.