Skip to content

Complexity cheat sheet

All bounds are average-case unless stated. n is the number of elements, k the number of buckets or ranges, V vertices and E edges.

Structure Access Search Insert Delete Space Notes
Array O(1) O(n) O(n) O(n) O(n) Insert/delete at the end is amortised O(1)
Dynamic array O(1) O(n) O(1)* O(1)* O(n) *amortised; resize copies
Singly linked list O(n) O(n) O(1) O(1) O(n) O(1) only with a reference to the node
Doubly linked list O(n) O(n) O(1) O(1) O(n) O(1) with a node reference
Stack / queue O(n) O(n) O(1) O(1) O(n) Top/front only
Hash table — O(1)† O(1)† O(1)† O(n) †O(n) worst case with collisions
Binary search tree O(log n)* O(log n)* O(log n)* O(log n)* O(n) *balanced; O(n) degenerate
Heap (min/max) O(1) top O(n) O(log n) O(log n) O(n) Build heap is O(n)
Trie O(m) O(m) O(m) O(m) O(n·m) m = key length
Graph (adjacency list) — O(V+E) O(1) O(1) O(V+E) Adjacency matrix is O(V²) space
Algorithm Best Average Worst Space Stable
Bubble O(n) O(n²) O(n²) O(1) Yes
Insertion O(n) O(n²) O(n²) O(1) Yes
Selection O(n²) O(n²) O(n²) O(1) No
Merge O(n log n) O(n log n) O(n log n) O(n) Yes
Quicksort O(n log n) O(n log n) O(n²) O(log n) No
Heapsort O(n log n) O(n log n) O(n log n) O(1) No
Counting O(n+k) O(n+k) O(n+k) O(k) Yes
Radix O(d(n+k)) O(d(n+k)) O(d(n+k)) O(n+k) Yes
Problem Complexity Notes
Linear search O(n) Works on unsorted data
Binary search O(log n) Requires sorted data
Quickselect O(n) average, O(n²) worst k-th element
BFS / DFS O(V+E) Graph traversal
Dijkstra (binary heap) O((V+E) log V) Non-negative weights
Bellman–Ford O(V·E) Handles negative weights, detects cycles
Floyd–Warshall O(V³) All-pairs shortest paths
Topological sort O(V+E) DAG only
Union–Find O(α(n)) ≈ O(1) Amortised, with path compression
Recurrence Result Example
T(n) = T(n/2) + O(1) O(log n) Binary search
T(n) = T(n/2) + O(n) O(n) Quickselect average
T(n) = 2T(n/2) + O(n) O(n log n) Merge sort
T(n) = 2T(n/2) + O(1) O(n) Tree traversal
T(n) = T(n−1) + O(1) O(n) Linear recursion
T(n) = T(n−1) + O(n) O(n²) Naive quicksort worst case
T(n) = 2T(n−1) + O(1) O(2ⁿ) Naive subsets
T(n) = T(n−1) + T(n−2) O(2ⁿ) Naive Fibonacci
  • Drop constants and lower-order terms: 3n² + 2n + 1 → O(n²).
  • Nested loops over the same input are usually O(n²); over two inputs, O(n·m).
  • Halving the problem each step is O(log n); sorting then scanning is O(n log n).
  • Recursion adds stack space: depth d costs O(d) memory.
  • Hash maps trade space for O(1) average lookup; the worst case is O(n).
  • String concatenation in a loop is O(n²) in many languages; use a builder or buffer.