Brain
EngineeringProblem Solving

Topics

The full checklist of data structures, algorithms and named patterns worth knowing, with what to know about each and which ones are already written up.

A coverage map rather than a tutorial. Use it to find the gap in what you know, then go to patterns for the template and collections for the Java API.

The three lists below overlap on purpose. Data structures are what you store things in, algorithms are what you do to them, and the named patterns are the combinations that keep reappearing in interview questions.

Data structures

StructureWhat to knowJava
ArrayFixed length, O(1) by index, O(n) to insert in the middle. Sorting unlocks two pointers and binary search.int[], Arrays
StringImmutable, so concatenation in a loop is O(n^2). Build with a builder.String, StringBuilder
Matrix or gridA 2D array is a graph with implicit neighbours. Keep one direction array, and check whether movement is 4 way or 8 way.int[][]
Hash map and hash setO(1) average, worst case O(log n) per bucket. A key needs equals and hashCode to agree, and must not mutate after insertion.HashMap, HashSet, LinkedHashMap
Ordered map and setSorted keys, plus floor, ceiling, higher, lower and range views. O(log n) for everything.TreeMap, TreeSet
Linked listSingly and doubly. A dummy head removes the empty and first node special cases. Reversal and merging are the two moves.Hand rolled ListNode, LinkedList
StackLast in, first out. Use the deque, not the legacy synchronised class.ArrayDeque
Queue and dequeFirst in, first out, or both ends in O(1). The deque is also the sliding window maximum structure.ArrayDeque
Heap or priority queueO(log n) insert and remove, O(1) peek. Iteration order is not sorted.PriorityQueue
Binary tree and BSTHeight, depth, the three DFS orders, level order. On a BST, inorder comes out sorted and the ordering property prunes half the search.Hand rolled TreeNode
TrieA tree keyed by character, so lookup costs word length rather than dictionary size.Hand rolled node with next[26]
GraphAdjacency list against adjacency matrix, directed against undirected, weighted against unweighted. The representation decides the algorithm.List<List<Integer>>
Disjoint setUnion find with path compression and union by rank, effectively constant per operation.Hand rolled DSU
Fenwick or segment treeRange queries that survive updates, O(log n) each. Fenwick for sums, segment tree for anything not subtractable.Hand rolled int[]
BitmaskAn integer as a set of flags, which makes subset enumeration a plain loop.int, long

Algorithms and techniques

TechniqueWhat to know
SortingO(n log n), custom comparators, stability, and the fact that most greedy solutions open with a sort.
Binary searchTwo forms: on an index, and on the answer when the question is the smallest value that works.
Two pointersOpposite ends on sorted input, or same direction with a read and a write pointer for in-place edits.
Fast and slow pointersCycle detection and finding the middle, in O(1) space.
Sliding windowFixed and variable size, usually paired with a hash map or a frequency array.
Prefix sum and difference arrayRange sums with no updates, and range updates with one read at the end.
RecursionBase case, progress toward it, and what the call stack is holding for you.
BacktrackingChoose, recurse, undo. Subsets, permutations, and constraint filling.
Divide and conquerMerge sort, quicksort, quickselect for the kth element in O(n) average.
GreedySort by the right key, then argue why a local choice cannot block a better global one.
Dynamic programmingMemoisation against tabulation, 1D and 2D states, subsequences, and 0/1 knapsack as the shape most others reduce to.
DFSReachability, connected components, and enumerating every path.
BFSShortest path on unweighted edges, and level by level work.
Topological sortOrdering under dependencies, and cycle detection as a side effect.
Union findMerging groups and answering whether two things are connected.
Shortest pathsDijkstra for non negative weights, Bellman-Ford when weights can be negative, Floyd-Warshall for all pairs on a small graph.
Minimum spanning treeKruskal with union find, or Prim with a heap.
Bit manipulationXOR cancelling pairs, clearing and isolating the lowest set bit, subset masks.
Math and number theoryGCD and LCM by Euclid, the sieve for primes, modular arithmetic to keep numbers in range.
GeometryCompare squared distances instead of taking roots, and use the cross product sign for turn direction.
Game theoryMinimax, and the rule that a position wins when some move leaves the opponent losing.
String matchingKMP and Rabin-Karp for substring search in linear time.
ConcurrencyThreads, locks, synchronized, and the standard producer and consumer setup.

The named patterns

The list most interview prep material is organised around. Each row jumps straight to the section holding that template, not to the top of the page.

#PatternJump to
1Two pointersTwo pointers
2Fast and slow pointersFast and slow pointers
3Sliding windowSliding window
4Merge intervalsMerge intervals
5Cyclic sortCyclic sort
6In-place reversal of a linked listLinked list surgery
7StackStack
8Monotonic stackMonotonic stack
9Hash mapsHashing
10Tree breadth first searchBinary tree traversal
11Tree depth first searchBinary tree traversal
12GraphsDFS and BFS
13Islands and matrix traversalMatrix traversal
14Two heapsTwo heaps
15SubsetsBacktracking
16Modified binary searchBinary search
17Bitwise XORBit manipulation
18Top k elementsHeap
19K-way mergeK-way merge
20Greedy algorithmsGreedy
210/1 knapsackDynamic programming
22BacktrackingBacktracking
23TrieTrie
24Topological sortTopological sort
25Union findUnion-Find
26Ordered setTreeSet
27Multi-threadingConcurrency
28MiscellaneousDesign

Still open

Every named pattern above now has a template. What is left is the deeper graph work, which is big enough to deserve its own page rather than a section: Dijkstra for non negative weights, Bellman-Ford when weights can go negative, Floyd-Warshall for all pairs on a small graph, and the two minimum spanning tree constructions, Kruskal with union find and Prim with a heap.

String matching is the other gap. KMP and Rabin-Karp both find a substring in linear time, and neither is hard, but they come up rarely enough that they are easy to keep putting off.

On this page