Skip to content
ΣDSA Patterns
Menu
Language

Complexity

Complexity & Big-O

A practical primer for coding interviews: what Big-O means, common bounds, how to analyze loops, and how space complexity fits in.

What Big-O measures

Time complexity describes how the work an algorithm does scales as the input size n grows. In interviews you almost always quote the worst-case Big-O; average case comes up for structures like hash maps.

Big-O drops constant factors and lower-order terms: 3n² + 100n + 5 is O(n²). The goal is a fast answer to “does this approach still work as n grows?”

Common bounds

Big-ONameTypical exampleWhen you see it
O(1)ConstantArray index, hash map avg get/putWork independent of input size
O(log n)LogarithmicBinary search, balanced BST lookupHalve the search space each step
O(n)LinearSingle pass, scan an arrayTouch each element once
O(n log n)LinearithmicGood sorts (merge/heap), many sort-then-scanSorting or divide-and-conquer merge
O(n²)QuadraticNested double loop, naive pairsEvery pair / every i,j
O(2ⁿ)ExponentialFull subset enumeration, naive recursionInclude/exclude each element
O(n!)FactorialAll permutationsOrderings (n must be tiny)

How to count loops

Space complexity

How much extra memory beyond the input? Output arrays are sometimes counted separately, clarify in the interview. Recursion depth d usually costs O(d) stack space.

Rough table by structure

StructureAccessSearchInsertNote
Array / listO(1)O(n)O(n)**Append may be amortized O(1)
Hash map / set-O(1) avgO(1) avgO(n) worst with bad hashing
Sorted arrayO(1)O(log n)O(n)Binary search enabled
Stack / queueO(1) endsO(n)O(1)End operations only
Min/max heapO(1) minO(n)O(log n)Top-K and priority
Balanced BST-O(log n)O(log n)Ordered traversal

Work at n = 1000

Logarithms below are base 2, which only changes the constant. At n = 1000, log2(n) is about 10. Naive recursive Fibonacci is Θ(φⁿ), about O(1.618ⁿ). Calling it O(2ⁿ) is a loose upper bound. Quote worst case unless you say average or amortized.

Big-OAt n = 1000Note
O(1)1Array index. Hash get/put is average-case, worst-case O(n).
O(log n)~10Binary search, balanced BST.
O(n)1,000One pass.
O(n log n)~10,000Mergesort, heapsort, Timsort.
O(n²)1,000,000Two nested passes.
O(n³)1,000,000,000Floyd–Warshall, three nested passes.
O(2ⁿ)2^1000Subset include/exclude. Materializing each subset is Θ(n · 2ⁿ).
O(n!)1000!All permutations.

Algebra

  1. Drop constants: O(2n) is O(n).
  2. Drop lower terms: O(n² + n) is O(n²).
  3. Different inputs stay different: a loop over a then a loop over b is O(a + b).
  4. Nested work multiplies: O(n) outside an O(m) body is O(n · m).
  5. Sequential work adds: O(n) then O(m) is O(n + m).

Early exit can improve the best case. Worst-case Big-O stays the worst path.

Where extra space comes from

Auxiliary space excludes the input. Say so when you quote it. Output storage is sometimes counted separately. Ask which one the interviewer wants. In-place means O(1) extra space. The input itself still occupies O(n).

SourceExtra space
A fixed set of scalarsO(1)
A string or array of length nO(n)
RecursionO(depth) stack frames
Recursive binary searchO(log n) stack. The loop form is O(1).
Hash map of the inputO(n)

Amortized costs

α(n) is the inverse Ackermann function. For every structure you will see in an interview it is at most 4. A hash table with a forced collision chain is O(n) per call and stays there. Amortized O(1) assumes a working hash.

OperationWorst one callAmortizedCondition
Dynamic array appendO(n)O(1)Geometric resize
Hash table insertO(n)O(1)Evenly spread hash, plus resize
Union-findO(n)O(α(n))Union by rank or size, and path compression
Splay treeO(n)O(log n)Amortized over a sequence of ops

Distinctions the structure table does not spell out

The live table already lists array, hash map, sorted array, stack/queue, heap, and balanced BST. These rows add the missing operations.

StructureOperationTimeNote
ArrayInsert or delete in the middleO(n)Elements shift
Singly linked listInsert or delete at the headO(1)
Singly linked listInsert after a node you holdO(1)Finding the node is a separate O(n)
Singly linked listDelete a node you holdO(n)You need the previous node, unless you copy the successor and are not at the tail
Doubly linked listDelete a node you holdO(1)
HeapBuild from n itemsO(n)Floyd's bottom-up build, not n pushes

Sorting

Stable means equal keys keep their original order.

AlgorithmBestAverageWorstExtra spaceStableNote
TimsortO(n)O(n log n)O(n log n)O(n)YesWhat Python actually runs
InsertionO(n)O(n²)O(n²)O(1)YesBest case is nearly sorted input
BubbleO(n)O(n²)O(n²)O(1)YesO(n) best case needs a swapped-flag exit
SelectionO(n²)O(n²)O(n²)O(1)No
MergesortO(n log n)O(n log n)O(n log n)O(n)Yes
HeapsortO(n log n)O(n log n)O(n log n)O(1)No
QuicksortO(n log n)O(n log n)O(n²)O(log n) avgNoWorst-case recursion depth is O(n), so extra space is O(n)
CountingO(n + k)O(n + k)O(n + k)O(k)Yesk is the key range. Integer keys
Radix (LSD)O(d(n + b))O(d(n + b))O(d(n + b))O(n + b)Yesd digits, b base
BucketO(n + k)O(n + k)O(n²)O(n)If the inner sort is stableAverage assumes a uniform spread

Graphs

Times assume an adjacency list. An adjacency matrix makes DFS and BFS O(V²). Dijkstra with a Fibonacci heap is O(E + V log V). Interviews expect the binary-heap bound. A topological sort of a graph that contains a cycle does not produce a valid order. Kahn's algorithm reports that by leaving nodes with remaining indegree.

AlgorithmTimeExtra spaceRequiresPattern
DFSO(V + E)O(V)graph-dfs
BFSO(V + E)O(V)Shortest path in hops, unweightedgrid-graph-bfs
DijkstraO((V + E) log V)O(V)Non-negative weights. Bound is a binary heapshortest-path-weighted
Bellman–FordO(VE)O(V)Negative weights allowed. One more pass after V − 1 rounds detects a negative cycleshortest-path-weighted
Floyd–WarshallO(V³)O(V²)All pairs. Negative edges allowed. dist[i][i] < 0 means a negative cycle—
Topological sortO(V + E)O(V)Directed acyclic graphtopological-sort
KruskalO(E log E)O(V)Undirected. Sort edges, then union-findminimum-spanning-tree
PrimO(E log V)O(V)Undirected and connected. Bound is a binary heap. Dense + array is O(V²)minimum-spanning-tree

Interview tips

Next step

Move into foundations on the roadmap, browse patterns, or open resources for platforms, books, and references, or the language cards: Python, TypeScript, C#.

For a visual take on these bounds, see math foundations - growth rates, logarithms, and summations.