Cheat Sheet

Big-O & Data Structures

Complexity tables you can scan in a minute: data structures, sorting, graph algorithms and the Java collections, with the JDK facts checked against the JDK 21 source.

8
Groups
JDK 21
Facts checked
1
Diagram
Index ยท Spring ยท SQL ยท Git ยท Docker/kubectl ยท Kafka/Rabbit CLI ยท Redis ยท Big-O
01
Chapter 1 - Growth rates

The Shapes That Matter

Big-O describes how the number of steps grows with input size n, ignoring constants. It tells you what happens when the data gets 10 times bigger, not which code is faster today.

Growth rates for n = 1 to 20 (operations, cut off at 400)
400 0 1 20 n (input size) n log n n^2 2^n n, log n and 1 hug the bottom axis: that is the point. Steepest first: 2^n n^2 n log n n log n 1
ClassNameTypical exampleDoubling n does what
O(1)ConstantArray index, hash lookup (average)Nothing
O(log n)LogarithmicBinary search, balanced tree lookupAdds one step
O(n)LinearScan an arrayDoubles the work
O(n log n)LinearithmicMerge sort, heap sort, sorting in generalA little more than doubles
O(n^2)QuadraticNested loops, insertion sortFour times the work
O(n^3)CubicNaive matrix multiply, Floyd-WarshallEight times the work
O(2^n)ExponentialSubsets, naive recursive FibonacciSquares the work
O(n!)FactorialAll permutationsUnusable beyond a dozen items
Reading the notation

O is an upper bound (usually the worst case, unless the table says average). Omega is a lower bound and Theta is both. In interviews "O" normally means "the tight worst case unless I say otherwise".

02
Chapter 2 - Data structures

Complexity of Core Data Structures

Average case unless a column says worst. "Amortised" means averaged over a sequence of operations.

StructureAccess by index/keySearchInsertDeleteSpaceGotcha
Array (fixed)O(1)O(n)O(n) shiftO(n) shiftO(n)Fixed size; insert in the middle moves everything
Dynamic array (ArrayList)O(1)O(n)O(1) amortised at end; O(n) elsewhereO(n) except lastO(n)A resize copies the whole array, but rarely
Singly linked listO(n)O(n)O(1) at head (or at a known node)O(1) at head; O(n) to find a nodeO(n)Poor cache locality; no backwards walk
Doubly linked list (LinkedList)O(n)O(n)O(1) at either endO(1) at either end or at a held nodeO(n)Index access walks from the nearer end
Stack / queue / deque (array based)n/aO(n)O(1) amortised at the endsO(1) at the endsO(n)ArrayDeque beats LinkedList for both
Hash tableO(1) averageO(1) averageO(1) averageO(1) averageO(n)Worst case O(n) with many collisions; resizing is O(n)
Binary search tree (unbalanced)n/aO(log n) average, O(n) worstO(log n) average, O(n) worstO(log n) average, O(n) worstO(n)Sorted insertion degrades it to a linked list
Balanced BST (AVL, red-black)n/aO(log n)O(log n)O(log n)O(n)Ordered iteration, range queries, floor and ceiling
B-tree / B+ treen/aO(log n)O(log n)O(log n)O(n)Wide nodes: few disk reads; database indexes
Binary heapMin or max: O(1)O(n)O(log n)Remove top: O(log n)O(n)Building from n items is O(n); not sorted
Trien/aO(L), L = key lengthO(L)O(L)O(total characters)Independent of the number of keys; memory hungry
Skip listn/aO(log n) expectedO(log n) expectedO(log n) expectedO(n)Randomised; used in sorted sets of some stores
Union-Find (with path compression and union by rank)n/afind: near O(1) (inverse Ackermann, amortised)union: samen/aO(n)Connected components, Kruskal
Segment treen/aRange query O(log n)Point update O(log n)n/aO(n)Build O(n)
Fenwick tree (BIT)n/aPrefix sum O(log n)Update O(log n)n/aO(n)Smaller and simpler than a segment tree for prefix sums
Bloom filtern/aO(k) hashesO(k)Not supportedFixed bitsFalse positives, never false negatives
Graph: adjacency listn/aEdge check O(degree)Add edge O(1)O(degree)O(V + E)Best for sparse graphs
Graph: adjacency matrixEdge check O(1)n/aO(1)O(1)O(V^2)Best for dense graphs
03
Chapter 3 - Sorting

Sorting Algorithms

The facts to memorise: which are n log n, which use extra memory, which are stable (equal items keep their order).

AlgorithmBestAverageWorstSpaceStableNote
Bubble sortO(n) with early exitO(n^2)O(n^2)O(1)YesTeaching only
Selection sortO(n^2)O(n^2)O(n^2)O(1)NoFewest swaps (at most n-1)
Insertion sortO(n)O(n^2)O(n^2)O(1)YesGreat on small or nearly sorted input
Shell sortO(n log n)Depends on gapsDepends on gapsO(1)NoInsertion sort with shrinking gaps
Merge sortO(n log n)O(n log n)O(n log n)O(n) for arraysYesPredictable; good for linked lists and external sorting
Quick sortO(n log n)O(n log n)O(n^2)O(log n) stackNoBad pivots cause the worst case; randomise or use median of three
Heap sortO(n log n)O(n log n)O(n log n)O(1)NoIn place with guaranteed bound, slower in practice (cache)
Tim sortO(n)O(n log n)O(n log n)O(n)YesMerge + insertion; exploits existing runs
Counting sortO(n + k)O(n + k)O(n + k)O(n + k)Yes (typical version)Integers in a small range k; not comparison based
Radix sortO(d (n + k))O(d (n + k))O(d (n + k))O(n + k)Yesd digits, base k; fixed-width keys
Bucket sortO(n + k)O(n + k) for uniform dataO(n^2)O(n + k)Depends on the inner sortNeeds evenly distributed input
04
Chapter 4 - Java sort facts

What the JDK Actually Does

Checked against the JDK 21 src.zip Javadoc of Arrays and List.

FactValue
Lower bound for comparison sortingOmega(n log n): no comparison sort can beat it in the worst case
Binary search needsSorted input; O(log n) steps; mid = lo + (hi - lo) / 2 avoids integer overflow
Arrays.sort(int[]) and other primitive arrays (JDK 21 Javadoc)Dual-Pivot Quicksort, documented as O(n log n) performance on all data sets
Arrays.sort(Object[]), Collections.sort, List.sortStable merge-based sort (the List.sort Javadoc calls it stable, adaptive and iterative); needs a consistent comparator
05
Chapter 5 - Graph and search algorithms

Algorithms You Will Be Asked About

V = vertices, E = edges.

AlgorithmTimeSpaceUseGotcha
Linear searchO(n)O(1)Unsorted dataFine for small n
Binary searchO(log n)O(1)Sorted array, or "first true" on a monotone conditionOff-by-one on bounds; overflow of lo + hi
BFSO(V + E)O(V)Shortest path in unweighted graphs, levelsMark visited when enqueuing
DFSO(V + E)O(V) recursion or stackConnectivity, cycles, topological orderDeep recursion can overflow the stack
Topological sort (Kahn or DFS)O(V + E)O(V)Dependency order in a DAGFails (no order) if there is a cycle
Dijkstra (binary heap)O((V + E) log V)O(V)Shortest paths, non-negative weightsWrong with negative edges
Bellman-FordO(V E)O(V)Negative edges, negative cycle detectionSlow on big graphs
Floyd-WarshallO(V^3)O(V^2)All pairs shortest pathsOnly for small V
Kruskal (MST)O(E log E)O(V)Minimum spanning tree with union-findSort edges first
Prim (MST, heap)O(E log V)O(V)Minimum spanning treeDense graphs may prefer the matrix version
Dynamic programming (table)States x transitionsStates (often reducible)Overlapping subproblemsState count drives the cost
BacktrackingExponential in generalO(depth)Subsets, permutations, constraint searchPrune early
06
Chapter 6 - Java collections

Java Collections Complexity

What the JDK documents and the constants in the JDK 21 source (HashMap constants and ArrayList growth read from src.zip).

Collectionget / containsadd / putremoveOrdered?Gotcha
ArrayListget(i) O(1); contains O(n)add at end O(1) amortised; add(i, x) O(n)remove(i) O(n); last element O(1)Insertion orderGrows by about 1.5 times (preferred growth is half the old capacity)
LinkedListget(i) O(n); contains O(n)add first or last O(1)ends O(1); by index or value O(n)Insertion orderIndex operations traverse from the nearer end; usually slower than ArrayList in practice
ArrayDequecontains O(n)addFirst, addLast O(1) amortisedpollFirst, pollLast O(1); remove(Object) O(n)Insertion orderNo null elements; faster than Stack and LinkedList as a stack or queue
HashMap / HashSetO(1) averageO(1) averageO(1) averageNoDefault capacity 16, load factor 0.75; resize doubles and rehashes
HashMap with colliding keysO(log n) in a treeified binsamesameNoA bin turns into a tree when it reaches 8 nodes and the table has at least 64 buckets; otherwise the table is resized instead. It turns back to a list at 6 or fewer
LinkedHashMapO(1)O(1)O(1)Insertion or access orderAccess order mode gives an LRU cache with removeEldestEntry
TreeMap / TreeSetO(log n)O(log n)O(log n)Sorted by keyJavadoc: guaranteed log(n) for containsKey, get, put and remove; no null keys with natural ordering
PriorityQueuepeek O(1); contains O(n)offer O(log n)poll O(log n); remove(Object) O(n)Heap order, not sortedIterating does not give sorted order
ConcurrentHashMapO(1) averageO(1) averageO(1) averageNoLock-free reads; compound check-then-act still needs computeIfAbsent or similar
CopyOnWriteArrayListO(1)O(n) (copies the array)O(n)Insertion orderFor read-mostly lists only
Collections.sort / List.sortn/aO(n log n)n/an/aStable; sorts an array copy then writes back (default List.sort)
String.concat in a loopn/aO(n^2) overalln/an/aUse StringBuilder for O(n)
List.contains in a loopn/aO(n*m)n/an/aPut one side in a HashSet
07
Chapter 7 - Limits and amortisation

Rules of Thumb and Amortisation

Use input limits in a problem statement to pick the target complexity. The thresholds below are planning heuristics, not measurements; real speed depends on language, memory access and hardware, and ~10^8 simple operations per second is only an order-of-magnitude guess.

If n is up toYou can afford aboutTypical algorithms
10 to 11O(n!)All permutations
20 to 25O(2^n)Subsets, bitmask DP
around 100 to 500O(n^3)Floyd-Warshall, triple loops
around 5,000 to 10,000O(n^2)Nested loops, simple DP tables
around 10^5 to 10^6O(n log n)Sorting, heaps, balanced trees, sweep lines
around 10^7 to 10^8O(n)One or a few passes, hashing
above thatO(log n) or O(1)Binary search, math formulas, precomputation
Amortised ideaExplanation
Dynamic array appendMost appends cost 1 step; a resize copies n items. Growth by a constant factor keeps the average per append constant: adding n elements costs O(n) in total (stated in the ArrayList Javadoc)
Growing by a fixed amount insteadAdding a fixed number of slots each time makes n appends cost O(n^2) in total
Hash table resizeRehash is O(n) but happens after n/2 more inserts, so inserts stay O(1) on average
Counting trickEach element is moved to a stack or queue at most a constant number of times, so total work is O(n) even with a nested loop (monotonic stack, sliding window, two pointers)
08
Chapter 8 - Common mistakes

Complexity Mistakes

โš  The ones that cost real time
  • Calling hash map operations O(1) without the caveat. It is O(1) on average with a good hash; worst case degrades (Java treeifies a long bin so it is O(log n) there).
  • Forgetting hidden costs. list.remove(0), String += in a loop, list.contains inside a loop and substring copies are all O(n).
  • Counting only loops. Recursion depth, sorting inside a loop and library calls count too.
  • Dropping a variable. BFS is O(V + E), not O(n). Two inputs need two variables.
  • Ignoring space. Merge sort is O(n) extra, recursion uses stack space, memoisation uses a table.
  • Confusing amortised with average. Amortised is a guarantee over a sequence; average is over random inputs.
  • Optimising constants first. Fix the algorithm class, then measure.
  • **Treating LinkedList as faster for inserts.** Finding the position costs O(n) and cache misses make it slower than ArrayList in most real programs.
09
Chapter 9 - Go deeper

Long-form pages and what was checked

TopicPage
Complexity analysis explainedComplexity
Arrays and dynamic arraysArray
Linked lists, stacks, queues, dequesLinked List, Stack, Queue, Deque
Hash maps and setsHash Map, Hash Set
Trees, heaps, triesBinary Tree, BST, Heap, Trie
Graph algorithmsGraph Basics, BFS, DFS, Shortest Path
SortingSorting
Java collectionsJava Collections Framework
DSA indexData Structures & Algorithms
Version note

Checked on 2026-10-31 against JDK 21 (21.0.2) src.zip: HashMap constants (default capacity 16, load factor 0.75, treeify threshold 8, untreeify threshold 6, minimum treeify capacity 64 and the "resize instead of treeify" comment), ArrayList growth (preferred growth of half the old capacity, so about 1.5 times) and its amortised-constant statement, TreeMap log(n) guarantee, PriorityQueue log(n) enqueue/dequeue and linear remove(Object)/contains notes, ArrayDeque amortised-constant and linear-exception notes, Arrays dual-pivot quicksort for primitives, and the List.sort stable-sort wording. The textbook complexities of data structures, sorting and graph algorithms are standard results listed from knowledge, not re-fetched from a source for this sheet; the n-limit table is a heuristic and is labelled as such. The inverse-Ackermann bound for union-find assumes both path compression and union by rank.