{} The Go Reference

Practice · Guide · Reference

DSA Cheat-Sheet

A one-page map of the structures and algorithms — their costs, when to reach for each, and the Go stdlib that already implements them. Built for revision and interview prep.

Practice Reference ⏱ 3 min read Complete

The whole track at a glance — costs, the right tool for a job, and the Go that already ships it. Each row links to the full page; skim to find the tool, then dive in.

🎯 How to read this

Complexities are average case unless noted. Big-O drops constants and lower-order terms — it describes how cost grows, which is what decides whether your code survives 10× the data.

Complexity at a glance

ClassNameExample in Go
O(1)constantm[key], s[i], len(s)
O(log n)logarithmicbinary search, balanced-tree lookup
O(n)linearone loop over a slice
O(n log n)linearithmicslices.Sort, merge sort
O(n²)quadraticnested loops over the same input
O(2ⁿ)exponentialnaive recursive subsets / Fibonacci

Data structures — cost & when

StructureAccessSearchInsertDeleteReach for it when
Array / sliceO(1)O(n)O(1)*O(n)dense indexed data; the default
Linked listO(n)O(n)O(1)†O(1)†O(1) splice at a held node (LRU)
Stack / queueO(1)O(1)LIFO / FIFO discipline
Hash tableO(1)O(1)O(1)fast lookup by key, unordered
BST (balanced)O(log n)O(log n)O(log n)ordered iteration, range queries
HeapO(1) peekO(log n)O(log n)always pop the min/max next
TrieO(L)O(L)O(L)prefix search, autocomplete
Union-findO(α(n))O(α(n))dynamic connectivity, merge groups

* amortized for append; † given a pointer to the node; α = inverse Ackermann (≈ constant).

Algorithm patterns

PatternUse it whenCost
Binary searchinput is sorted, or a monotonic predicateO(log n)
Sortingorder matters; unlocks search & two-pointerO(n log n)
Two pointerssorted array, pair/triplet, in-placeO(n)
Sliding windowcontiguous subarray / substringO(n)
BFSshortest path in hops (unweighted)O(V + E)
DFSreachability, cycles, topological orderO(V + E)
Backtrackingenumerate candidates, undo on dead endsexponential, pruned
Dynamic programmingoverlapping subproblems + optimal substructurestates × transition
Greedya local choice is provably globaloften O(n log n)

The Go standard library already has it

NeedReach for
Sort a sliceslices.Sort, slices.SortFunc, sort.Slice
Binary searchslices.BinarySearch, sort.Search
Map / setbuilt-in map; a set is map[T]struct{}
Priority queuecontainer/heap
Doubly linked listcontainer/list
Min / max of twomin, max builtins (Go 1.21)
Clone a slice / mapslices.Clone, maps.Clone

Decision shortcuts — “I need to…”

✅ Pick a structure or pattern by what you're doing

  • …look up by key, fasthash table
  • …keep data sorted / range queriesbalanced BST (or sorted slice + binary search)
  • …always take the smallest/largest nextheap
  • …prefix match / autocompletetrie
  • …LIFO or FIFO orderingstack / queue
  • …shortest path in an unweighted graphBFS
  • …visit everything / detect a cycleDFS
  • …all combinations or permutationsbacktracking
  • …optimize over overlapping subproblemsdynamic programming
  • …a provably-optimal local choicegreedy
  • …track connectivity / merge groups as edges arriveunion-find

🐹 Interview reflex: brute force first, then trade space for time

State the costs and edge cases out loud, write a correct brute force, then name the bottleneck and the pattern that removes it — a hash set turns an O(n²) duplicate scan into O(n); sorting unlocks two pointers; memoization collapses exponential recursion to polynomial. And in real Go, prefer the standard library over a hand-rolled structure unless asked to build it.

Check your understanding

Score: 0 / 5

1. You need average O(1) lookup, insert and delete by key, and order doesn't matter. Which structure?

Hashing gives average O(1) for all three; a BST is O(log n) and keeps order you don't need here. Reach for a map (a set is map[T]struct{}).

2. What's the right tool for the shortest path in hops on an unweighted graph?

BFS visits in ring order, so it reaches every node by a fewest-edges path first. DFS may find a longer path first; Dijkstra is for weighted graphs.

3. Greedy makes change for 6 from coins {1,3,4} as 4+1+1 = 3 coins. Why prefer DP here?

Greedy only works when the coin system has the greedy-choice property. For {1,3,4} making 6, greedy gives 3 coins but DP gives the optimal 2 (3+3).

4. Edges arrive over time and you repeatedly ask 'are these two nodes connected yet?' Which structure fits?

Dynamic connectivity is union-find's specialty: Union to join, Find to compare roots, both effectively O(1). A one-shot BFS/DFS can't cheaply answer the query as edges keep arriving.

5. You need the k largest items from a huge stream without sorting it all. Which structure?

Keep only k elements in a min-heap; its root is the smallest kept, so any larger newcomer replaces it. You never hold more than k or sort the whole input — O(n log k), the canonical top-k pattern.

Comments

Sign in with GitHub to join the discussion.