Cheatsheet: Big-O Complexity

Last updated 2026-11-23

Growth rates (fastest to slowest)

Common complexities and an example of each

O(1)        hash lookup, array index
O(log n)    binary search, heap push/pop
O(n)        single pass, BFS/DFS on n nodes
O(n log n)  sorting, n heap operations
O(n²)       all pairs, nested loops
O(2^n)      all subsets
O(n!)       all permutations

What fits the input size

Rough limits for a 1–2 second time limit

n ≤ 10        O(n!), O(n · 2^n)
n ≤ 20        O(2^n), bitmask DP
n ≤ 500       O(n³)
n ≤ 5,000     O(n²)
n ≤ 10^5      O(n log n)
n ≤ 10^6      O(n)
n ≥ 10^9      O(log n) or O(1), e.g. binary search on the answer

Data structures (average case)

Operation costs

Structure            Access    Search    Insert    Delete
Array / list         O(1)      O(n)      O(n)*     O(n)*
Stack / queue        —         O(n)      O(1)      O(1)
Linked list          O(n)      O(n)      O(1)**    O(1)**
Hash map / set       —         O(1)      O(1)      O(1)
Balanced BST         O(log n)  O(log n)  O(log n)  O(log n)
Binary heap          O(1) min  O(n)      O(log n)  O(log n) pop
Trie (key length L)  —         O(L)      O(L)      O(L)

*  append/pop at the end is amortized O(1)
** given a pointer to the node

Worst cases worth mentioning

Hash map: O(n) if many keys collide
Unbalanced BST: O(n) if it degenerates into a list
Heap: building from a list with heapify is O(n), not O(n log n)

Sorting

Time and space

Algorithm       Best        Average     Worst       Space     Stable
Quicksort       O(n log n)  O(n log n)  O(n²)       O(log n)  no
Merge sort      O(n log n)  O(n log n)  O(n log n)  O(n)      yes
Heapsort        O(n log n)  O(n log n)  O(n log n)  O(1)      no
Timsort         O(n)        O(n log n)  O(n log n)  O(n)      yes
Insertion sort  O(n)        O(n²)       O(n²)       O(1)      yes
Counting sort   O(n + k)    O(n + k)    O(n + k)    O(k)      yes

Timsort is what Python's sorted() and Java's sort for objects use.

Graphs and trees (V vertices, E edges)

Algorithm costs

BFS / DFS                  O(V + E)
Topological sort (Kahn)    O(V + E)
Dijkstra (binary heap)     O((V + E) log V)
Bellman-Ford               O(V · E)
Floyd-Warshall             O(V³)
Prim / Kruskal (MST)       O(E log V)
Union-Find, per operation  ~O(1) amortized (inverse Ackermann)
Tree traversal             O(n) time, O(h) space

Patterns

Typical cost of each pattern

Two pointers / sliding window   O(n)
Prefix sums                     O(n) build, O(1) range query
Binary search                   O(log n), or O(n log(range)) on the answer
Monotonic stack                 O(n): each index pushed and popped once
Top-k with a heap of size k     O(n log k)
Backtracking: subsets           O(n · 2^n)
Backtracking: permutations      O(n · n!)
1D DP                           O(n) states × cost per state
2D DP (e.g. LCS)                O(n · m)

FAQ