← All cheat sheets
⏱️

Big-O & Complexity

Operation costs, sorting, and how to guess the target complexity from input size.

Guess complexity from n (the single most useful trick)

Given the constraint on n, the intended solution is usually:

n ≤Target complexity
10–12O(n!) — permutations / brute force
~20O(2ⁿ) — subsets / bitmask DP
~500O(n³)
~5,000O(n²)
~10⁶O(n log n) or O(n)
> 10⁶ / 10⁹O(log n) or O(1)

Data structure operations (average)

StructureAccessSearchInsertDelete
ArrayO(1)O(n)O(n)O(n)
Hash map / setO(1)O(1)O(1)
Stack / QueueO(n)O(n)O(1)O(1)
Binary heapO(1) peekO(n)O(log n)O(log n)
Balanced BSTO(log n)O(log n)O(log n)O(log n)

Sorting

AlgorithmTimeSpaceStable
QuicksortO(n log n) avg, O(n²) worstO(log n)No
MergesortO(n log n)O(n)Yes
HeapsortO(n log n)O(1)No
Counting / RadixO(n + k)O(n + k)Yes

Rules of thumb

  • Drop constants and lower-order terms: O(2n + 5) → O(n).
  • Nested loop over the same n → O(n²); halving each step → O(log n).
  • Recursion cost = (number of nodes) × (work per node). Master theorem for divide & conquer.
  • Hash map trades O(n) space for O(1) lookup — the classic time/space swap.
SDE-2 Launchpad · Big-O & Complexity cheat sheet