Skip to content
BytePatterns

Big-O cheat sheet

Time and space complexity of every data structure and algorithm on BytePatterns, from hash tables to Dijkstra, each row linked to its animated lesson.

Updated 78 rows94 lessons linkedPrints cleanly — use your browser's print

How to read it

  • n is the input size. Constants and smaller terms are dropped: 3n + 5 is O(n).
  • Time is the worst case unless the cell says avg or amortized (cheap on average over a long run of operations, even if one of them is expensive).
  • Space is extra space — memory on top of the input, not counting the output. Recursion counts: its call stack is space.
  • V and E are vertices and edges; m and n are the two lengths in a two-string or grid problem. Any other letter is defined in its row.
  • Constant or logarithmic
  • Linear or n log n
  • Polynomial
  • Exponential or factorial

New to the notation? The Big-O module takes it one idea at a time: What Is Big-O?, O(1) and O(n), O(log n) and Halving, O(n²) and Nested Loops, Comparing Complexities.

Growth orders

The shape matters more than the numbers: an O(n²) solution that is fine at n = 100 is hopeless at n = 100,000. The chart shows the shape for small n; the table shows the step counts at sizes you meet in real constraints.

How the common complexity classes growSteps against input size n from 1 to 20, cut off at 60 steps. O(1) stays flat and O(log n) barely rises; O(n) climbs steadily and O(n log n) a little faster; O(n²) leaves the chart before n reaches 8, O(2ⁿ) before 6 and O(n!) before 5.15101520input size n →steps →O(n!)O(2n)O(n2)O(n log n)O(1)O(log n)O(n)
Steps against n, from n = 1 to 20, cut off at 60 steps.
Steps at real input sizes
Ordern = 10n = 1,000n = 1,000,000
O(1) constant111
O(log n) logarithmic3.31019.9
O(n) linear101,0001,000,000
O(n log n) linearithmic33.29,966≈ 107
O(n2) quadratic1001,000,000≈ 1012
O(2n) exponential1,024≈ 10301≈ 10301029
O(n!) factorial3,628,800≈ 102567≈ 105565708
From the constraint to the complexity
Input limitUsually fits
n ≤ 10O(n!)
n ≤ 20O(2n)
n ≤ 500O(n3)
n ≤ 5,000O(n2)
n ≤ 106O(n log n)
n ≤ 107O(n)
largerO(log n) or O(1)

A rule of thumb for a one-second limit, assuming roughly 10⁷–10⁸ simple steps per second. Constant factors and the language move it; the order of the rows does not change.

Data structures

What each operation costs. Card titles link to the lesson that animates it.

  • Array (dynamic)

    Read / write by index
    O(1)
    Search (unsorted)
    O(n)
    Append at the end
    O(1) amortized
    Insert / delete in the middle
    O(n)
    Space
    O(n)

    Every element after the gap has to shift.

  • Singly linked list

    Reach the k-th node
    O(n)
    Search
    O(n)
    Insert / delete at the head
    O(1)
    Insert / delete after a known node
    O(1)
    Space
    O(n)

    See also: Insert and Delete

  • Doubly linked list

    Push / pop at either end
    O(1)
    Unlink a node you hold
    O(1)
    Search
    O(n)
    Space
    O(n)

    The prev pointer is what makes unlinking O(1) — the core of an LRU cache.

  • Stack

    Push / pop / peek
    O(1)
    Search
    O(n)
    Space
    O(n)
  • Queue / deque

    Enqueue / dequeue
    O(1)
    Peek front
    O(1)
    Search
    O(n)
    Space
    O(n)

    Removing from the front of a plain array is O(n) — use a deque or a ring buffer.

    See also: Circular Queue

  • Hash table (map / set)

    Lookup
    O(1) avgO(n) worst
    Insert
    O(1) avgO(n) worst
    Delete
    O(1) avgO(n) worst
    Space
    O(n)

    The worst case is every key in one bucket. No order: iterating sorted costs O(n log n).

    See also: When Hashing Fails

  • Binary heap

    Peek min / max
    O(1)
    Push
    O(log n)
    Pop min / max
    O(log n)
    Build from n items (heapify)
    O(n)
    Search
    O(n)
    Space
    O(n)

    See also: Heapify and Sift · Priority Queue

  • Binary search tree

    Search / insert / delete
    O(h)
    …when balanced
    O(log n)
    …when degenerate (a chain)
    O(n)
    In-order walk
    O(n)
    Space
    O(n)

    h is the height. Sorted input builds the chain.

    See also: BST Insert and Search · Tree Depth and Balance

  • Trie

    Insert a word
    O(L)
    Search a word
    O(L)
    Starts-with a prefix
    O(L)
    Space
    O(total characters)

    L is the length of the word or prefix — independent of how many words are stored.

    See also: Prefix Search · Trie vs Hash Set

  • Union-find (disjoint set)

    Find / union, both optimisations
    O(α(n)) amortized
    …union by size only
    O(log n)
    …neither
    O(n)
    Space
    O(n)

    α is the inverse Ackermann function: at most 4 for any input that fits in memory.

    See also: Path Compression · Union by Rank or Size

  • Graph — adjacency list

    Is there an edge u → v?
    O(deg u)
    Visit all neighbours of u
    O(deg u)
    Add an edge
    O(1)
    Space
    O(V + E)

    The default for sparse graphs — which is most interview graphs.

    See also: Graph Basics

  • Graph — adjacency matrix

    Is there an edge u → v?
    O(1)
    Visit all neighbours of u
    O(V)
    Add an edge
    O(1)
    Space
    O(V2)

    Worth it only when the graph is dense or V is small.

Sorting

Comparison sorts cannot beat O(n log n) in the worst case; counting and radix sort step around that bound by not comparing.

Sorting algorithms: best, average and worst time, extra space and stability
AlgorithmBestAverageWorstSpaceStableNotes
Bubble sortO(n)O(n2)O(n2)O(1)YesThe O(n) best case needs the stop-when-no-swaps check.
Selection sortO(n2)O(n2)O(n2)O(1)NoAt most n − 1 swaps — its one selling point.
Insertion sortO(n)O(n2)O(n2)O(1)YesFast on nearly sorted input.
Merge sortO(n log n)O(n log n)O(n log n)O(n)Yes
Quick sortO(n log n)O(n log n)O(n2)O(log n)NoWorst case from repeatedly bad pivots; the stack then grows to O(n).
Heap sortO(n log n)O(n log n)O(n log n)O(1)No
Counting sortO(n + k)O(n + k)O(n + k)O(n + k)Yesk is the range of values. Integers (or keys) only.
Radix sortO(d·(n + b))O(d·(n + b))O(d·(n + b))O(n + b)Yesd digits in base b, one stable pass per digit.

Searching

Searching: time and extra space
AlgorithmTimeSpaceNotes
Search in a rotated sorted arrayO(log n)O(1)Distinct values. Duplicates can force O(n).
Find a peak elementO(log n)O(1)
Binary search on the answerO(Clog R)O(1)R is the size of the answer range, C the cost of one feasibility check.
Search a sorted 2-D matrix (staircase)O(m + n)O(1)m rows, n columns; each step discards a row or a column.

Array, list and string techniques

Array, list and string techniques: time and extra space
AlgorithmTimeSpaceNotes
Two pointersO(n)O(1)
Sliding windowO(n)O(k)Each element enters and leaves once; k is what the window has to remember.
Prefix sumsO(n) buildO(1) per queryO(n)
Subarray sum with a hash mapO(n)O(n)
Kadane's maximum subarrayO(n)O(1)
Product of array except selfO(n)O(1)Not counting the output array.
Dutch national flag (3-way partition)O(n)O(1)
Fast & slow pointers (cycle detection)O(n)O(1)
Reverse a linked listO(n)O(1)Iterative. Recursion costs O(n) stack.
Monotonic stackO(n) amortizedO(n)Every element is pushed once and popped at most once.
Sliding window maximum (deque)O(n)O(k)
KMP string matchingO(n + m)O(m)n text, m pattern.
Rabin–Karp rolling hashO(n + m) avgO(n·m) worstO(1)Worst case when every window's hash collides.
Z-algorithmO(n + m)O(n + m)

Heaps and ordering

Heaps and ordering: time and extra space
AlgorithmTimeSpaceNotes
Top-k with a heap of size kO(n log k)O(k)
Top-k frequent with bucketsO(n)O(n)
K-way mergeO(N log k)O(k)N items in total across k sorted lists.
Running median (two heaps)O(log n) addO(1) medianO(n)
Merge intervalsO(n log n)O(n)The sort dominates; the sweep is O(n).
Meeting rooms (min-heap of end times)O(n log n)O(n)

Graphs and grids

Graphs and grids: time and extra space
AlgorithmTimeSpaceNotes
Shortest path, unweighted (BFS)O(V + E)O(V)
Grid flood fill / islandsO(R·C)O(R·C)R rows × C columns: each cell visited once.
Topological sort (Kahn)O(V + E)O(V)
Dijkstra (binary heap)O((V + E) log V)O(V)Non-negative weights only.
Bellman–FordO(V·E)O(V)Handles negative weights and detects negative cycles.
Kruskal's MSTO(E log E)O(V)Sort the edges, then union-find.
Prim's MST (binary heap)O(E log V)O(V)
Bipartite check (2-colouring)O(V + E)O(V)
Strongly connected componentsO(V + E)O(V)

Dynamic programming

Dynamic programming: time and extra space
AlgorithmTimeSpaceNotes
Climbing stairs / Fibonacci-styleO(n)O(1)Two rolling variables instead of the table.
House robberO(n)O(1)
Coin change (fewest coins)O(n·A)O(A)n coin types, A the amount.
0/1 knapsackO(n·W)O(W)W is the capacity; one row, filled right to left.
Longest common subsequenceO(m·n)O(m·n)O(min(m, n)) space if only the length is needed.
Edit distanceO(m·n)O(m·n)
Longest increasing subsequence (DP)O(n2)O(n)
Longest increasing subsequence (tails)O(n log n)O(n)
Paths in a gridO(m·n)O(n)One row of the table at a time.
Interval DP (matrix-chain order)O(n3)O(n2)

Recursion and backtracking

Recursion and backtracking: time and extra space
AlgorithmTimeSpaceNotes
Naive recursive FibonacciO(2n)O(n)An upper bound; the tight bound is about 1.618ⁿ.
Memoized recursion (Fibonacci)O(n)O(n)
All subsetsO(n·2n)O(n)Not counting the output.
All permutationsO(n·n!)O(n)Not counting the output.
N-queensO(n!)O(n)Upper bound; pruning cuts most of it.

Math and bits

Math and bits: time and extra space
AlgorithmTimeSpaceNotes
GCD (Euclid)O(log min(a, b))O(1)
Fast exponentiationO(log n)O(1)Iterative squaring; n is the exponent.
Sieve of EratosthenesO(n log log n)O(n)
XOR to find the single numberO(n)O(1)
Count set bits (clear the lowest 1)O(k)O(1)k is the number of 1 bits — at most the word size.
Power-of-two checkO(1)O(1)

bytepatterns.com/cheatsheets/big-o — every row links to an animated lesson there.

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.