Time Complexity Cheat Sheet

Quick reference for Big-O notation and algorithm complexity

Complexity Overview

Big-O notation describes the upper bound of an algorithm's growth rate. Here's how common complexities compare:

O(1)
Constant
O(log n)
Logarithmic
O(n)
Linear
O(n log n)
Linearithmic
O(n^2)
Quadratic
O(2^n)
Exponential

Quick Rule

For n = 10^6 (1 million), O(n) takes ~1 second, O(n^2) takes ~10^6 seconds (11 days). Always aim for O(n log n) or better for large inputs.

Data Structures

Array / Vector

OperationAverageWorst
Access by indexO(1)O(1)
SearchO(n)O(n)
Insert at endO(1)*O(n)
Insert at startO(n)O(n)
DeleteO(n)O(n)

*Amortized for vector

Linked List

OperationAverageWorst
Access by indexO(n)O(n)
SearchO(n)O(n)
Insert at headO(1)O(1)
Insert at positionO(n)O(n)
Delete (with ref)O(1)O(1)

Stack / Queue

OperationAverageWorst
Push / EnqueueO(1)O(1)
Pop / DequeueO(1)O(1)
Top / FrontO(1)O(1)
SearchO(n)O(n)

Hash Table (unordered_map)

OperationAverageWorst
InsertO(1)O(n)
SearchO(1)O(n)
DeleteO(1)O(n)

Worst case occurs with hash collisions

Binary Search Tree (map/set)

OperationAverageWorst
InsertO(log n)O(log n)
SearchO(log n)O(log n)
DeleteO(log n)O(log n)
Min / MaxO(log n)O(log n)

C++ map/set use Red-Black Trees (balanced)

Heap (priority_queue)

OperationTime
PushO(log n)
Pop (extract max/min)O(log n)
Top (peek)O(1)
Build heapO(n)

Sorting Algorithms

AlgorithmBestAverageWorstSpaceStable
Quick Sort O(n log n) O(n log n) O(n^2) O(log n) No
Merge Sort O(n log n) O(n log n) O(n log n) O(n) Yes
Heap Sort O(n log n) O(n log n) O(n log n) O(1) No
Bubble Sort O(n) O(n^2) O(n^2) O(1) Yes
Insertion Sort O(n) O(n^2) O(n^2) O(1) Yes
Selection Sort O(n^2) O(n^2) O(n^2) O(1) No
Counting Sort O(n+k) O(n+k) O(n+k) O(k) Yes

C++ STL Uses Introsort

std::sort() uses Introsort (Quick + Heap + Insertion), guaranteeing O(n log n) worst case. std::stable_sort() uses Merge Sort.

Searching Algorithms

AlgorithmTimeSpaceRequirement
Linear Search O(n) O(1) None
Binary Search O(log n) O(1) Sorted array
Hash Table Lookup O(1) avg O(n) Hash function
BST Search O(log n) O(1) Balanced tree

Graph Algorithms

AlgorithmTimeSpaceUse Case
DFS O(V + E) O(V) Path finding, cycle detection
BFS O(V + E) O(V) Shortest path (unweighted)
Dijkstra O((V+E) log V) O(V) Shortest path (positive weights)
Bellman-Ford O(V * E) O(V) Shortest path (negative weights)
Floyd-Warshall O(V^3) O(V^2) All-pairs shortest path
Topological Sort O(V + E) O(V) DAG ordering
Union-Find O(alpha(n)) O(n) Disjoint sets, MST

Quick Tips for Interviews

Common Constraints

  • n <= 10: O(n!) or O(2^n) is okay (brute force)
  • n <= 20: O(2^n) backtracking
  • n <= 500: O(n^3) is okay
  • n <= 5000: O(n^2) is okay
  • n <= 10^6: O(n log n) or O(n) needed
  • n <= 10^8: O(n) or O(log n) needed

Space-Time Tradeoffs

  • HashMap: Trade O(n) space for O(1) lookup
  • Memoization: Trade space for avoiding recomputation
  • Precomputation: Trade initialization time for query speed