Data Structures & Algorithms Cheatsheet

Pattern Cheat Table

Use this Data Structures & Algorithms reference while you build software engineering projects, review code, or refresh the syntax you reach for most.

How To Use This

Read the problem statement, find the phrase or input shape below, and start with the pattern in that row. The complexity column is what a correct solution should land on, so if your idea is slower than the listed target you are on the wrong pattern.

Order of operations before writing any code:

  1. Read the constraints first. They pin the target complexity, which usually eliminates all but two or three patterns.
  2. Find the signal phrase in the master table below.
  3. State the approach and its complexity out loud before typing.
  4. Handle the empty and single-element case in the first two lines.

Master Signal Table

Signal in the problemPatternTypical complexity
sorted array, find a pair summing to a targettwo pointers from both endsO(n) time, O(1) space
triplets or quadruples summing to a targetsort plus inner two pointersO(n^(k−1))
unsorted array, find a pair summing to a targethash map complement lookupO(n) time, O(n) space
contiguous subarray or substring, longest or shortestsliding windowO(n)
subarray of a fixed size kfixed sliding windowO(n)
subarray sum equals k, values may be negativeprefix sums plus a hash mapO(n)
count subarrays with exactly k distinctat most k, minus at most k−1O(n)
many range-sum queries, no updatesprefix sum arrayO(n) build, O(1) query
many range updates, one final readdifference arrayO(1) update, O(n) finalize
range queries interleaved with point updatesFenwick tree or segment treeO(log n) each
sliding window maximum or minimummonotonic dequeO(n)
next greater or previous smaller elementmonotonic stackO(n)
balanced parentheses, nesting, undo the last thingstackO(n)
largest rectangle in a histogram, trapping rain watermonotonic stack, or two pointersO(n)
in-place filter, dedupe, or partition keeping orderread and write pointersO(n), O(1) space
sort 0s, 1s, and 2s in one passDutch national flag, three pointersO(n), O(1) space
sorted input and you need an index or a boundarybinary search, lower_bound templateO(log n)
first or last occurrence, insertion position, floor, ceilingbinary search boundary templateO(log n)
rotated sorted arraybinary search on the sorted halfO(log n)
"minimum k such that", "minimize the maximum"binary search on the answerO(n log R)
huge numeric range but a cheap feasibility checkbinary search on the answerO(n log R)
kth largest or kth smallest, one queryquickselectO(n) average
kth largest under a stream, or top kheap of size kO(n log k)
merge k sorted lists or arraysmin-heap of one head per listO(N log k)
running median of a streamtwo heaps, max and minO(log n) per insert
repeatedly need the cheapest remaining optionpriority queueO(log n) per operation
middle of a linked list, cycle detectionfast and slow pointersO(n), O(1) space
reverse a list or a sublist in placethree-pointer reversalO(n), O(1) space
the head of a list may be removed or replaceddummy sentinel nodeO(n)
prefix queries, autocomplete, dictionary of wordstrieO(m) per word
word search in a grid against many wordstrie plus DFS backtrackingO(rc · 3^L)
maximum XOR of a pairbinary trie over bitsO(32n)
sorted output from a tree, kth smallest in a BSTinorder traversalO(n), O(h + k)
the answer at a node needs its children's answerspostorder DFS aggregationO(n)
per-level aggregate, right-side view, minimum depthBFS level orderO(n)
shortest path, unweighted graph or gridBFSO(V + E)
shortest path, non-negative weightsDijkstra with a heapO((V + E) log V)
shortest path, weights are 0 or 10-1 BFS with a dequeO(V + E)
shortest path with negative edgesBellman-FordO(V · E)
shortest path with at most k hopsBellman-Ford with a snapshot per roundO(k · E)
all-pairs shortest paths, V ≤ 400Floyd-WarshallO(V³)
minimum steps in a state space, moves are reversibleBFS over encoded statesO(states · moves)
count islands, flood fill, connected regionsDFS or BFS per unvisited cellO(rc)
distance from every cell to the nearest sourcemulti-source BFSO(rc)
connectivity under incremental edge additionsunion-findO(α(n)) per operation
detect a cycle in an undirected graphunion-find, or DFS with a parent checkO(V + E)
detect a cycle in a directed graphthree-color DFS, or Kahn's length checkO(V + E)
minimum spanning treeKruskal with union-find, or Prim with a heapO(E log E)
group items by an equivalence relationunion-findO(n · α(n))
prerequisites, dependencies, valid orderingtopological sort, Kahn'sO(V + E)
minimum rounds or semesters under dependenciesKahn's, level by levelO(V + E)
longest path in a DAGDP in topological orderO(V + E)
2-colorable, no odd cycleBFS or DFS bipartite checkO(V + E)
"return all" subsets, permutations, or combinationsbacktrackingO(2ⁿ · n), O(n! · n)
constraint satisfaction: N-Queens, Sudoku, coloringsbacktracking with occupied setsexponential with pruning
"count the number of ways"DPusually O(n) to O(n²)
minimum or maximum over a sequence of choicesDPO(n) to O(n²)
take-or-skip each item toward a capacity, one copy each0/1 knapsack, capacity descendingO(n · W)
unlimited copies of each item toward a targetunbounded knapsack, capacity ascendingO(n · W)
count combinations reaching a targetunbounded DP, items in the outer loopO(n · W)
count permutations reaching a targetunbounded DP, target in the outer loopO(n · W)
longest increasing subsequencepatience DP with binary searchO(n log n)
two strings compared or transformed2D DP on prefix pairsO(nm), O(min) space
minimum edits between two stringsedit distance DPO(nm)
grid paths, minimum path sum, maximal square2D grid DP, rolled to one rowO(rc), O(c) space
optimal over every split of an intervalinterval DP, iterate by lengthO(n³)
n ≤ 20 and you must track a visited setbitmask DPO(2ⁿ · n)
intervals: merge or union themsort by start, extend a running blockO(n log n)
maximum non-overlapping intervals keptsort by end, activity selectionO(n log n)
minimum removals to make intervals disjointtotal minus the maximum keptO(n log n)
minimum rooms, machines, or resources at oncesort by start, min-heap of end timesO(n log n)
minimum points or arrows hitting every intervalsort by end, greedy placementO(n log n)
can you reach the end, furthest reach so fargreedy invariantO(n), O(1) space
a locally best choice is provably safegreedy with an exchange argumentO(n log n)
every element appears twice except oneXOR everythingO(n), O(1) space
subsets of a small set, or a visited maskbitmask enumerationO(2ⁿ)
powers of two, lowest set bit, popcountbit tricksO(1)
GCD, LCM, modular inverse, huge exponentnumber theory, Euclid and fast powerO(log n)
primes up to n, or many factorizationssieve of EratosthenesO(n log log n)

Constraints To Target Complexity

The constraint is the strongest hint in the entire problem statement. Judges run roughly 10⁸ simple operations per second.

Max nTargetPatterns that fit
≤ 10O(n!) · O(2ⁿ · n)full permutation backtracking
≤ 20–22O(2ⁿ · n)bitmask DP, subset enumeration
≤ 100O(n³)Floyd-Warshall, interval DP
≤ 1,000–5,000O(n²)2D DP, quadratic LIS, pairwise loops
≤ 10⁵–10⁶O(n log n)sort, heap, binary search, sweep line, patience LIS
≤ 10⁷–10⁸O(n)hash map, two pointers, sliding window, prefix sums, Kadane
≤ 10¹⁸O(log n) · O(1)binary search on the answer, math, fast exponentiation

Data Structure Selection

What you needStructureCost
index by positionarray or dynamic arrayO(1) read, O(n) middle insert
membership, counting, groupinghash set or hash mapO(1) average
sorted iteration, ranges, floor and ceilingbalanced BST, TreeMap, std::mapO(log n)
the smallest or largest remaining itemheapO(log n) push and pop, O(1) peek
LIFO, undo, nesting, next greaterstackO(1)
FIFO, level order, BFSdequeO(1) both ends
window extremesmonotonic dequeO(1) amortized
prefix strings, autocompletetrieO(m) per word
connectivity under mergesunion-findO(α(n))
range query plus point updateFenwick or segment treeO(log n)
range query, no updatesprefix sumsO(1) query
set of ≤ 64 elements, fast set algebrabitmask integerO(1) per operation

Structural Rewrites

Recognizing that a problem is a different problem in disguise is often the whole solution.

Looks likeActually is
a grida graph, cells are vertices and 4 or 8 neighbors are edges
a puzzle with legal movesa graph over encoded states, solved by BFS
"minimum moves" with reversible movesunweighted shortest path, so BFS
equal numbers of 0s and 1smap 0 to −1 and look for a prefix sum of 0
"at most k distinct"a sliding window with a frequency map
"exactly k"at most k, minus at most k−1
Russian doll envelopes, chain of pairssort, then longest increasing subsequence
longest palindromic subsequenceLCS of the string with its reverse
partition into two equal halvessubset sum to total / 2, a 0/1 knapsack
minimum removals to de-overlaptotal minus the maximum non-overlapping kept
find the duplicate in 1..n in O(1) spaceFloyd cycle detection on the index-to-value function
the longest path in a DAGDP in topological order, linear
ratios or offsets between grouped itemsweighted union-find
deletions from a connectivity structureprocess the timeline in reverse so deletions become unions
"minimize the maximum" or "maximize the minimum"binary search on the answer with a feasibility check

Wrong-Pattern Warning Signs

You reached forIt breaks whenUse instead
sliding window on sumsthe array has negative valuesprefix sums plus a hash map
Dijkstraany edge weight is negativeBellman-Ford
greedy coin changedenominations are arbitraryDP, unbounded knapsack
greedy 0/1 knapsack by densityitems cannot be splitDP, O(n · W)
a single visited set for a directed cyclethe graph has a diamond shapethree-color DFS
two pointersthe array is unsorted and cannot be sortedhash map
binary searchthe predicate is not monotonelinear scan or a different pattern
a hash mapyou need order, ranges, or the minimumbalanced BST or heap
list.pop(0) as a queuen is large, this is O(n) per callcollections.deque
backtracking to countsubproblems repeatDP or memoization
negating weights for a longest paththe graph has cyclesonly valid on a DAG
a rolled DP arrayyou must reconstruct the chosen itemskeep the full table

Universal Correctness Checklist

Run this list before declaring a solution done. Most rejected submissions fail on one of these, not on the algorithm.

  • Empty input. Zero-length array, empty string, None root, no edges.
  • Single element. Many two-pointer and window solutions index a[1] implicitly.
  • All duplicates, and all identical values.
  • Already sorted, and reverse sorted. These are quicksort's and greedy's worst cases.
  • Negative numbers and zero. They break sum windows, product problems, and if not x guards.
  • Integer overflow. Use long for sums in Java and C++, and lo + (hi - lo) / 2 for midpoints.
  • 1-indexed input. Size arrays n + 1 or subtract 1 consistently.
  • Disconnected graphs. Loop over every vertex as a potential traversal start.
  • Self-loops and parallel edges in graph input.
  • Recursion depth. Python raises past about 1,000 frames, so deep recursion needs an explicit stack.
  • Copy before recording in backtracking. out.append(path) stores a live reference.
  • Undo unconditionally after every recursive call, including on early returns.
  • Restore mutated input if the caller still needs it.
  • State the final complexity, time and space, and say which variable n refers to.