Complexity Analysis
- Define Big-O, Θ and Ω precisely and use them correctly when you state the cost of a solution
- Derive amortized costs (slice
append, two-stack queue) and explain why amortized ≠ average - Solve common recurrences with the Master theorem or a recursion tree
- Predict when constants and cache behaviour beat asymptotics, and prove it with a Go benchmark
- Quote the cost of Go built-ins (map, slice, sort,
container/heap) without guessing
TL;DR
- Big-O is an upper bound, Ω a lower bound, Θ a tight bound. In interviews "O(n)" usually means "Θ(n) in the worst case" — say which case you mean.
- Read the constraints first. With ≈10⁸ simple operations per second as a budget,
n ≤ 10⁵rules out O(n²);n ≤ 20invites O(2ⁿ). - Amortized O(1) means a sequence of n operations costs O(n) total — individual calls can still take O(n). That is a p99 latency story, not just a math story.
- Space includes the recursion stack and any copies you make (
slices.Clone,[]rune(s), string concatenation). - Master theorem: for
T(n) = a·T(n/b) + f(n), comparef(n)withn^(log_b a); the bigger one wins, a tie adds a log factor. - Constants matter at real sizes. A contiguous slice scan can beat a map or linked list by a large factor because of cache lines and prefetching — measure with
testing.B. - Go facts to know cold: map ops O(1) average,
appendamortized O(1),slices.SortO(n log n) pdqsort (not stable),heap.InitO(n),heap.Push/PopO(log n).
When to reach for it
Always — but the signals that complexity is the crux of the question are:
- The prompt states input limits (
1 ≤ n ≤ 10⁵). Those numbers tell you the intended complexity before you think about the algorithm. - The interviewer asks "can you do better?" — they want you to name the current bound and the theoretical floor (e.g. you must read every element, so Ω(n)).
- A design discussion mentions latency SLOs or memory budgets: "the fraud check must answer in 5 ms at p99", "the dedup set must fit in 2 GB".
- Code that is "fast on my laptop" falls over in production with 100× data — almost always a hidden O(n²) (nested loop over a list, string concatenation in a loop,
slices.Containsinside a loop).
Rough budget table (assuming ≈10⁸ simple ops/s; Go often does better, but plan conservatively):
| Input size n | Feasible complexity | Typical technique |
|---|---|---|
| ≤ 10–12 | O(n!) | permutations, brute-force search |
| ≤ 20–25 | O(2ⁿ), O(n·2ⁿ) | subsets, bitmask DP, backtracking |
| ≤ 500 | O(n³) | Floyd–Warshall, interval DP |
| ≤ 5,000 | O(n²) | 2D DP, all pairs |
| ≤ 10⁶ | O(n log n) | sorting, heaps, binary search |
| ≤ 10⁸ | O(n) | single pass, two pointers, hashing |
| larger | O(log n), O(1) | math, binary search on answer |
Core concepts
Big-O, Θ and Ω
f(n) = O(g(n))if there are constants c > 0 and n₀ withf(n) ≤ c·g(n)for all n ≥ n₀. Upper bound.f(n) = Ω(g(n))iff(n) ≥ c·g(n)for all n ≥ n₀. Lower bound.f(n) = Θ(g(n))if both hold. Tight bound.
Bounds and cases are orthogonal. Quicksort's worst case is Θ(n²) and its average case is Θ(n log n). "Comparison sorting is Ω(n log n)" is a lower bound over all comparison algorithms in the worst case. When you say "my solution is O(n log n)" in an interview, you are implicitly claiming the worst case unless you add "on average" or "amortized" — be explicit, because hash maps and quickselect are exactly where interviewers probe.
Common growth classes, slowest to fastest growing: O(1) < O(log n) < O(√n) < O(n) < O(n log n) < O(n²) < O(2ⁿ) < O(n!). Rules you apply without thinking: drop constants (O(3n) = O(n)), keep the dominant term (O(n² + n) = O(n²)), and keep independent variables separate — a grid is O(R·C), a graph is O(V + E), and merging two lists is O(n + m), not O(n).
Amortized analysis: why append is O(1)
A Go slice is a header (ptr, len, cap) over a backing array. When len == cap, append allocates a bigger array and copies everything. A single append is therefore O(n) in the worst case, yet n appends cost O(n) in total, so each is amortized O(1).
Aggregate argument (doubling): to reach n elements you copied 1 + 2 + 4 + … + n/2 < n elements across all growths, plus n writes: under 2n work total. Any constant growth factor r > 1 works — the copy total is bounded by roughly n/(r−1), so a factor of 1.25 costs about 4n copies: still linear.
Accounting (banker's) argument: charge every append 3 "coins": one pays for the write, two are saved. When the array doubles from k to 2k, the k/2 elements appended since the last growth have saved k coins — exactly enough to pay for copying the k elements.
Go's actual policy (runtime growslice, Go 1.18+): capacity doubles while the slice is small (under 256 elements), then the factor smoothly decreases toward ≈1.25×, and the result is rounded up to an allocator size class. Exact capacities vary by version and element size, so never depend on them:
package main
import "fmt"
func main() {
var s []int
prev := cap(s)
for i := range 5000 {
s = append(s, i)
if cap(s) != prev {
fmt.Printf("len=%5d cap %5d -> %5d\n", len(s), prev, cap(s))
prev = cap(s)
}
}
}
Amortized O(1) is a worst-case guarantee over a sequence. Average-case O(1) (hash maps) is a statement about random inputs. Neither promises a fast individual call: a slice growing from 8M to 10M elements copies 64 MB in one append. In a payment API with a 50 ms p99 budget, pre-size with make([]T, 0, n) when you know n.
Space complexity
Count auxiliary space (beyond the input) unless asked otherwise, and include:
- Recursion depth. DFS on a degenerate tree (a linked list) of 10⁶ nodes uses 10⁶ frames. Go goroutine stacks start at a few KB and grow by copying, up to a default maximum of 1 GB on 64-bit platforms, so Go survives depths that crash Python's default limit — but each frame still costs memory and the copy costs time.
- Hidden copies.
[]rune(s),[]byte(s),strings.Split,slices.Clone,maps.Clone, and sub-slicing that retains a large backing array (memory you think is freed but is not). - Output space. Generating all subsets is O(n·2ⁿ) space just for the answer; say whether you are counting it.
Recursion, recurrences and the Master theorem
For divide-and-conquer recurrences of the form T(n) = a·T(n/b) + f(n) with a ≥ 1 and b > 1, let the critical exponent be c = log_b a (the cost of the leaves is n^c):
| Case | Condition | Result | Example |
|---|---|---|---|
| 1 — leaves dominate | f(n) grows slower than n^c | Θ(n^c) | Tree traversal: a = 2, b = 2, f = O(1) → Θ(n) |
| 2 — balanced | f(n) = Θ(n^c · log^k n) | Θ(n^c · log^(k+1) n) | Merge sort: a = 2, b = 2, f = n → Θ(n log n); binary search: a = 1, b = 2, f = 1 → Θ(log n) |
| 3 — root dominates | f(n) grows faster than n^c (plus a regularity condition) | Θ(f(n)) | a = 2, b = 2, f = n² → Θ(n²) |
Karatsuba multiplication (a = 3, b = 2, f = n) lands in case 1: Θ(n^1.585). The theorem does not cover subtract-and-conquer recurrences; solve those directly:
T(n) = T(n−1) + O(1)→ Θ(n) (linear recursion over a list).T(n) = T(n−1) + O(n)→ Θ(n²) (quicksort with a bad pivot every time).T(n) = 2·T(n−1) + O(1)→ Θ(2ⁿ) (naive include/exclude recursion).
When in doubt, draw the recursion tree: work per level × number of levels. Merge sort does n work on each of log₂ n levels:
Constants, memory hierarchy and cache effects
Asymptotics compare growth; production compares nanoseconds. Rough, CPU-dependent numbers: an L1 hit costs ≈1 ns, L2 ≈3–5 ns, L3 ≈10–20 ns, and a main-memory access ≈80–100 ns. Data moves in cache lines (64 bytes on most x86-64 CPUs, 128 bytes on Apple silicon). Consequences you can rely on:
- Sequential beats pointer-chasing. Summing a
[]intstreams through cache lines and the hardware prefetcher keeps up; summing acontainer/listjumps to a random heap address per node. Both are O(n), but the list is typically several times slower and also adds GC scanning work. []Tbeats[]*Tfor iteration-heavy code: values are contiguous, pointers scatter.- Small n favours simple structures. A linear scan over 8–16 elements can beat a map lookup (hashing has a fixed cost). Measure before "optimizing" a tiny lookup into a map.
- Interface dispatch and allocation are constants too.
slices.Sort(generic) usually beatssort.Sort(interface method calls); avoiding an allocation per element often matters more than shaving a log factor.
Prove it with a benchmark rather than arguing (Go 1.24+ b.Loop):
package perf
import (
"container/list"
"testing"
)
const n = 1 << 20
var (
sink int
slice = make([]int, n)
ll = newList(n)
)
func newList(size int) *list.List {
l := list.New()
for i := range size {
l.PushBack(i)
}
return l
}
func BenchmarkSumSlice(b *testing.B) {
for b.Loop() {
total := 0
for _, v := range slice {
total += v
}
sink = total
}
}
func BenchmarkSumList(b *testing.B) {
for b.Loop() {
total := 0
for e := ll.Front(); e != nil; e = e.Next() {
total += e.Value.(int)
}
sink = total
}
}
Cost of Go built-ins
| Operation | Cost | Notes |
|---|---|---|
m[k], m[k] = v, delete(m, k) | O(1) average | Per-map random hash seed resists hash flooding; worst case degrades with collisions |
for k, v := range m | O(n), can be proportional to allocated size | Random order; maps do not shrink after deletes |
len(x) for slice, string, map, channel | O(1) | Stored in the header |
append(s, x) | amortized O(1) | O(len) on the growth step |
append(s, t...), copy(dst, src) | O(len(t)) | memmove under the hood |
s[i:j] | O(1) | Shares the backing array: aliasing and retention |
slices.Insert, slices.Delete | O(n) | Shift the tail |
slices.Contains, slices.Index | O(n) | Inside a loop this is your hidden O(n²) |
slices.Sort, sort.Slice, sort.Ints | O(n log n) | pdqsort since Go 1.19; not stable |
slices.SortStableFunc, sort.SliceStable | O(n log n) compares, O(n log² n) swaps | Stable (insertion sort + in-place merge) |
slices.BinarySearch, sort.Search | O(log n) | Input must be sorted by the same order |
heap.Init | O(n) | Bottom-up heapify |
heap.Push, heap.Pop, heap.Fix, heap.Remove | O(log n) | container/heap |
list.PushFront, list.Remove, list.MoveToFront | O(1) | container/list, given the *Element |
s + t on strings | O(len(s) + len(t)) | Repeated in a loop: O(n²) total — use strings.Builder |
strings.Builder.WriteString | amortized O(len) | Same growth strategy as slices |
s[i] on a string | O(1) | Returns a byte, not a rune |
[]rune(s), utf8.RuneCountInString(s) | O(n) | Decodes UTF-8 |
string(b), []byte(s) | O(n) | Copies (the compiler elides some cases, e.g. m[string(b)]) |
strings.Index, strings.Contains | ≈ linear in practice | SIMD byte search with a Rabin–Karp fallback |
slices.Sorted(maps.Keys(m)) | O(n log n) | Deterministic iteration (Go 1.23+) |
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Brute force | Obviously correct, tiny code | Often O(n²) or worse | n is small, or as a correctness oracle for tests |
| Sort first | O(1)–O(log n) extra space, enables two pointers / binary search | O(n log n), destroys original order unless you copy | Memory is tight or order-based logic follows |
| Hash map / set | O(1) average lookups, single pass | O(n) extra memory, random order, worse constants for tiny n | n is large and lookups dominate |
| Precompute (prefix sums, tables) | O(1) queries after O(n) build | Build cost and memory; stale if data changes | Many queries over static data |
| Memoization | Turns exponential recursion into polynomial | Memory for the cache; recursion depth | Overlapping subproblems |
| Approximate structures (Bloom, HLL) | Sublinear memory | Bounded error | Exactness not required (see Data Structures Inside Real Systems) |
In practice
A quick empirical sanity check: time your function at n, 2n and 4n. If the time roughly doubles, it is linear; slightly more than doubles, n log n; quadruples, quadratic. It catches the hidden slices.Contains-in-a-loop before code review does.
Problem 1 — Contains Duplicate (LeetCode 217)
Problem. Given an integer slice, report whether any value appears at least twice.
Approach. Three answers with different trade-offs — the point of the exercise is to say the trade-off: nested loops (no memory), sort then compare neighbours (O(1) extra if you may mutate), or a set (fastest, O(n) memory).
// O(n²) time, O(1) extra space.
func containsDuplicateBrute(nums []int) bool {
for i := range nums {
for j := i + 1; j < len(nums); j++ {
if nums[i] == nums[j] {
return true
}
}
}
return false
}
// O(n log n) time. O(n) extra here because we clone; O(1) if mutating the input is allowed.
func containsDuplicateSort(nums []int) bool {
s := slices.Clone(nums)
slices.Sort(s)
for i := 1; i < len(s); i++ {
if s[i] == s[i-1] {
return true
}
}
return false
}
// O(n) average time, O(n) extra space.
func containsDuplicateSet(nums []int) bool {
seen := make(map[int]struct{}, len(nums))
for _, v := range nums {
if _, ok := seen[v]; ok {
return true
}
seen[v] = struct{}{}
}
return false
}
Complexity. As commented. Mention that the map version has O(n²) worst case under adversarial collisions in theory, which Go mitigates with a random per-map seed.
Problem 2 — Pow(x, n) (LeetCode 50)
Problem. Compute xⁿ for a float x and an integer n (possibly negative) faster than n multiplications.
Approach. Fast exponentiation: x^n = (x^(n/2))², times x if n is odd. The recursive form is T(n) = T(n/2) + O(1) → Θ(log n) by Master case 2 (a = 1, b = 2). The iterative form walks the bits of n.
func myPow(x float64, n int) float64 {
if n < 0 {
x, n = 1/x, -n // safe here: Go int is 64-bit, LeetCode n fits in 32 bits
}
result := 1.0
for n > 0 {
if n&1 == 1 {
result *= x
}
x *= x
n >>= 1
}
return result
}
// powRec shows the classic bug: calling powRec(x, n/2) twice instead of
// once gives T(n) = 2T(n/2) + O(1) = Θ(n), silently losing the speed-up.
func powRec(x float64, n int) float64 {
if n == 0 {
return 1
}
half := powRec(x, n/2)
if n%2 == 0 {
return half * half
}
return half * half * x
}
Complexity. O(log n) time; O(1) space iterative, O(log n) stack recursive.
Problem 3 — Implement Queue using Stacks (LeetCode 232)
Problem. Build a FIFO queue using only stack operations (push to top, pop from top).
Approach. Two stacks: push onto in; when out is empty, pour all of in into out (reversing order). Each element is moved at most once from in to out, so n operations do O(n) total work — amortized O(1) each, with occasional O(n) pours.
type Queue[T any] struct {
in, out []T
}
func (q *Queue[T]) Push(v T) { q.in = append(q.in, v) }
func (q *Queue[T]) Pop() (T, bool) {
var zero T
if len(q.out) == 0 {
for i := len(q.in) - 1; i >= 0; i-- {
q.out = append(q.out, q.in[i])
}
clear(q.in) // drop references so the GC can reclaim them
q.in = q.in[:0]
}
if len(q.out) == 0 {
return zero, false
}
last := len(q.out) - 1
v := q.out[last]
q.out[last] = zero
q.out = q.out[:last]
return v, true
}
Complexity. Push O(1) amortized (slice growth), Pop amortized O(1), worst-case O(n). O(n) space.
Problem 4 — Fibonacci Number (LeetCode 509)
Problem. Return F(n) where F(0) = 0, F(1) = 1.
Approach. The naive recursion T(n) = T(n−1) + T(n−2) + O(1) grows like φⁿ ≈ 1.618ⁿ because the same subproblems are recomputed. Keeping only the last two values removes both the repetition and the memory.
func fibNaive(n int) int { // Θ(φⁿ) time, O(n) stack
if n < 2 {
return n
}
return fibNaive(n-1) + fibNaive(n-2)
}
func fib(n int) int { // O(n) time, O(1) space
a, b := 0, 1
for range n {
a, b = b, a+b
}
return a
}
Complexity. Naive Θ(φⁿ); iterative O(n) time, O(1) space. (Matrix exponentiation gets O(log n), a nice follow-up.)
Practice list
- Easy: Contains Duplicate (217), Fibonacci Number (509), Climbing Stairs (70), Implement Queue using Stacks (232)
- Medium: Pow(x, n) (50), Sort an Array (912) — implement merge sort and state its recurrence, Kth Largest Element in an Array (215) — compare heap O(n log k) with quickselect O(n) average / O(n²) worst, Top K Frequent Elements (347), Sqrt(x) (69) by binary search
- Hard: Median of Two Sorted Arrays (4) — the O(log(min(n, m))) bound is the whole problem, Count of Smaller Numbers After Self (315)
Common pitfalls
- Hidden linear operations in loops:
slices.Contains,strings.Index,s = s + x, orappend([]T{x}, s...)(prepend) inside a loop. Symptom: an endpoint that is fine with 1k rows times out with 100k. - Forgetting the sort. "I use two pointers, so it's O(n)" — after an O(n log n) sort.
- Ignoring recursion stack space, then claiming O(1) space for a recursive DFS.
- Treating map operations as guaranteed O(1). They are average-case; also, a map that grew to 10M entries keeps that memory after deletes. Symptom: RSS never comes down after a batch job.
- Conflating amortized with per-call latency. A big
appendor map growth inside a hot request path shows up as periodic p99 spikes; pre-size withmake. - Mixing variables: calling an O(R·C) grid traversal "O(n)" without defining n, or O(V + E) graph work "O(n²)".
- Sub-slice retention: keeping
big[:10]alive pins the whole backing array. Useslices.Clonewhen you keep a small piece of a large buffer.
Interview angle
- State time and space unprompted, for both the brute force and the optimized solution, and name the case (worst / average / amortized).
- Use the constraints as a hint aloud: "n is up to 10⁵, so I'm aiming for O(n log n) or better."
- Know the floor: "We must read every transaction, so Ω(n); my O(n) solution is optimal." That ends the "can you do better?" loop.
- Follow-ups to expect: "What if the data does not fit in memory?" (external sort, streaming, approximate structures), "What if this runs a million times per second?" (constants, allocation, cache), "What is the worst case for your hash map?"
- Architect twist: translate complexity into capacity — 10M accounts × 64 bytes per entry ≈ 640 MB for an in-memory index; does it fit on one node? See Back-of-the-Envelope Estimation.
- Red flags: saying O(1) for
slices.Contains, not knowing that sorting costs O(n log n), or claiming "hash maps are always O(1)".
Self-check
1. Why is appending n elements to a Go slice O(n) total even though some appends copy the whole slice?
Because capacity grows geometrically. The copies happen at sizes that form a geometric series (1, 2, 4, …), whose sum is bounded by a constant times n. With doubling, total copies are under n; with Go's ≈1.25× factor for large slices it is still a constant multiple of n. So each append is amortized O(1), even though an individual append is O(n).
2. What is the difference between amortized O(1) and average-case O(1)?
Amortized is a worst-case bound on the total cost of any sequence of operations, divided by the number of operations — no probability involved (slice append, two-stack queue). Average-case is an expectation over a distribution of inputs (hash maps assuming a good hash). An adversary can break an average-case bound; it cannot break an amortized one.
3. Solve T(n) = 2T(n/2) + O(n), T(n) = T(n/2) + O(1), and T(n) = 2T(n−1) + O(1).
- Merge-sort shape: a = 2, b = 2,
n^(log_2 2) = nequals f(n) → case 2 → Θ(n log n). - Binary-search shape: a = 1, b = 2,
n^0 = 1equals f(n) → Θ(log n). - Subtract-and-conquer, not covered by the Master theorem: each level doubles the calls, n levels → Θ(2ⁿ).
4. You must check 10⁵ incoming transaction IDs against 10⁵ known IDs. Compare three approaches.
Nested loops: 10¹⁰ comparisons — too slow. Sort both and merge with two pointers: O(n log n) time, O(1) extra if you can sort in place. Build a set of known IDs: O(n) average time, O(n) memory. With 10⁵ IDs either of the last two is fine; at 10⁹ IDs that do not fit in memory you move to external sorting or a Bloom filter pre-check.
5. Why can a linked list traversal be several times slower than a slice traversal when both are O(n)?
The slice is contiguous: each 64-byte cache line brings several elements, and the hardware prefetcher predicts the next lines. List nodes live at scattered heap addresses, so each step can be a cache miss costing on the order of 100 ns, plus the GC has to scan more pointers. Big-O hides these constant factors.
6. A teammate's recursive DFS over a tree is "O(1) space". Is that right?
No. The call stack holds one frame per level, so space is O(h) where h is the tree height: O(log n) for a balanced tree, O(n) for a degenerate one. In Go the goroutine stack grows to accommodate it (up to 1 GB by default on 64-bit), but the memory is real.
7. Scenario: a settlement batch API has a 200 ms p99 but spikes to 900 ms every few minutes. Profiling shows runtime.growslice and map growth. What do you do?
The spikes are the O(n) steps of amortized growth landing on individual requests. Pre-size slices and maps with make([]T, 0, n) / make(map[K]V, n) when n is known, reuse buffers across requests (carefully, e.g. with sync.Pool), or move very large structures out of the request path. Verify with pprof and a benchmark before and after.
Exercise
Write three implementations of "has this transaction ID been seen?" over n IDs — slice with slices.Contains, sorted slice with slices.BinarySearch, and map[string]struct{} — and benchmark them with testing.B at n = 10, 100, 10⁴, 10⁶ (use b.Loop() and a package-level sink).
Done when you have: a table of ns/op per size, the crossover point where the map starts winning (it is not n = 1), a -benchmem column showing allocations, and one paragraph explaining the result in terms of Big-O and constants. Bonus: run go test -bench . -cpuprofile cpu.out and find runtime.mapaccess (or the Swiss-table equivalent) in go tool pprof.
Further reading
- Introduction to Algorithms (CLRS), chapters on growth of functions, recurrences (Master theorem) and amortized analysis
- Steven Skiena, The Algorithm Design Manual — chapter 2 on algorithm analysis, with a pragmatic tone
- Rob Pike, "Arrays, slices (and strings): The mechanics of 'append'" — The Go Blog
- Go source:
runtime/slice.go(growslice) and thesort/slicespackage documentation - Ulrich Drepper, "What Every Programmer Should Know About Memory" (2007)
Related
- Arrays & Hashing — the first place you trade memory for time.
- Pattern Cheat Sheet & Practice Plan — constraints-to-pattern mapping.
- Back-of-the-Envelope Estimation — complexity turned into capacity numbers.
- Memory, GC & Escape Analysis — why allocations are a constant you can see.
- Testing & Benchmarking — writing trustworthy benchmarks.
- Profiling & Performance — finding the hidden O(n²) in production.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).