Learn

Every data structure and algorithm, organized by family. Each page follows the same structure: overview, intuition, recognition, visualization, pseudocode, implementations, complexity, when (not) to use, alternatives, mistakes, interview patterns, problems.

Fundamentals

Arrays, strings, matrices and linked lists — the building blocks everything else is made of.

All 8 →
Stack & Queue

LIFO and FIFO containers, deques, monotonic variants and priority queues.

All 7 →
Hashing

Hash tables, maps, sets and how collisions are handled.

All 6 →
Trees

Binary trees, balanced search trees, tries, segment and Fenwick trees, B-trees.

All 11 →
Binary Tree
▶ viz

A hierarchical structure where every node has at most two children, the foundation of BSTs, heaps and expression trees.

O(n) search · O(n) space
Binary Search Tree
▶ viz

A binary tree where every left descendant is smaller and every right descendant is larger, giving O(h) ordered search, insert and delete.

O(log n) search · O(n) space
AVL Tree
▶ viz

A self-balancing BST that keeps every node's subtree heights within 1 of each other using rotations, guaranteeing O(log n) operations.

O(log n) search · O(n) space
Red-Black Tree
▶ viz

A self-balancing BST that colors nodes red or black and enforces color rules so that no path is more than twice as long as any other.

O(log n) search · O(n) space
N-ary Tree
▶ viz

A rooted tree in which each node can have any number of children, stored as a child list, and traversed with the same DFS/BFS ideas as binary trees.

O(n) search · O(n) space
Trie
▶ viz

A tree keyed by characters where each root-to-node path spells a prefix, giving O(L) insert, lookup and prefix search independent of how many words are stored.

O(L) search · O(N · L · σ) space
Segment Tree
▶ viz

A binary tree over array intervals that answers range queries (sum, min, max, gcd) and point or range updates in O(log n).

O(n) search · O(n) space
Fenwick Tree
▶ viz

A compact array-based tree that supports prefix-sum queries and point updates in O(log n) using the binary representation of indices.

O(log n) search · O(n) space
Interval Tree
▶ viz

A balanced BST of intervals keyed by start, augmented with the maximum end in each subtree, to find all intervals overlapping a point or range in O(log n + k).

O(log n) search · O(n) space
B-Tree

A balanced multiway search tree with wide nodes holding many keys, designed to minimize disk or cache-line reads for very large ordered data.

O(log n) search · O(n) space
B+ Tree

A B-tree variant that stores all records in linked leaf nodes and uses internal nodes only as a routing index, giving fast point lookups and sequential range scans.

O(log n) search · O(n) space
Heaps

Priority-ordered complete trees behind priority queues and heap sort.

All 4 →
Graphs

Directed, undirected, weighted graphs and their representations.

All 8 →
Specialized Structures

Union-Find, sparse tables, Bloom filters, caches and skip lists.

All 6 →
Searching

Linear, binary, ternary, jump, exponential search and quickselect.

All 6 →
Sorting

Comparison sorts, linear-time sorts and the hybrids used in practice.

All 11 →
Bubble Sort
▶ viz

Repeatedly swap adjacent out-of-order pairs so the largest remaining element bubbles to the end each pass.

O(n²) · O(1) space
Selection Sort
▶ viz

Repeatedly select the minimum of the unsorted suffix and swap it into place; exactly n−1 swaps.

O(n²) · O(1) space
Insertion Sort
▶ viz

Build a sorted prefix by inserting each new element into its correct place among the ones before it.

O(n²) · O(1) space
Merge Sort
▶ viz

Split the array in half, sort each half recursively, then merge the two sorted halves in linear time.

O(n log n) · O(n) space
Quick Sort
▶ viz

Pick a pivot, partition elements into smaller and larger sides, and recursively sort each side.

O(n²) · O(log n) space
Heap Sort
▶ viz

Build a max-heap in place, then repeatedly swap the root to the end and restore the heap.

O(n log n) · O(1) space
Counting Sort
▶ viz

Count occurrences of each key in a small integer range, then place elements by prefix sums — linear time, no comparisons.

O(n + k) · O(n + k) space
Radix Sort
▶ viz

Sort integers digit by digit from least significant to most, using a stable counting sort per digit.

O(d·(n + b)) · O(n + b) space
Bucket Sort
▶ viz

Distribute elements into buckets by value range, sort each bucket, and concatenate — linear on uniform data.

O(n²) · O(n + k) space
Shell Sort
▶ viz

Insertion sort over elements h apart with a shrinking gap sequence, finishing with a plain insertion sort.

O(n^1.5) · O(1) space
TimSort
▶ viz

Adaptive, stable hybrid of merge sort and insertion sort that exploits existing sorted runs; the default sort in Python and Java.

O(n log n) · O(n) space
Two Pointers

Opposite-direction, same-direction, fast & slow pointers and partitioning.

All 4 →
Sliding Window

Fixed, variable and frequency windows over contiguous ranges.

All 3 →
Prefix Techniques

Prefix sums, suffix sums, difference arrays, prefix XOR and 2D prefix sums.

All 5 →
Recursion & Backtracking

Exhaustive search over subsets, permutations, boards and mazes.

All 8 →
Divide & Conquer

Split, solve, combine — and when the recurrence pays off.

All 2 →
Greedy

Locally optimal choices that provably yield a global optimum.

All 8 →
Activity Selection

Pick the maximum number of mutually compatible activities by repeatedly taking the one that finishes earliest.

O(n log n) · O(1) space
Interval Scheduling

The family of interval problems: unweighted selection (greedy by finish), interval partitioning into minimum rooms (greedy by start with a min-heap), and weighted selection (DP with binary search).

O(n log n) · O(n) space
Fractional Knapsack

Maximize value in a capacity-limited knapsack when items can be taken in fractions: take items in decreasing value-per-weight order.

O(n log n) · O(1) space
Huffman Coding

Build an optimal prefix-free binary code by repeatedly merging the two least frequent symbols with a min-heap.

O(n log n) · O(n) space
Job Sequencing with Deadlines

Schedule unit-length jobs with deadlines and profits to maximize total profit: take jobs in profit order and place each in the latest free slot before its deadline.

O(n log n + n · α(n)) · O(n + maxD) space
Gas Station (Circular Tour)

Find the unique start on a circular route from which a car can complete the loop, in one pass: whenever the running tank goes negative, restart from the next station.

O(n) · O(1) space
Merge Intervals

Sort intervals by start and sweep once, extending the current interval while the next one overlaps and emitting it when a gap appears.

O(n log n) · O(n) space
Greedy Algorithms

Build a solution by repeatedly taking the locally best choice — correct only when an exchange argument proves that choice never hurts.

O(n log n) · O(1) space
Dynamic Programming

Overlapping subproblems, optimal substructure, memoization and tabulation.

All 25 →
Dynamic Programming
▶ viz

Solve a problem by defining subproblems whose answers are reused, so exponential recursion collapses to polynomial time.

O(states × transition cost) · O(states), often reducible to O(1 row) space
Memoization (Top-Down DP)
▶ viz

Write the natural recursion, then cache every result by its arguments so each distinct subproblem is computed once.

O(states × transition cost) · O(states) memo + O(recursion depth) stack space
Tabulation (Bottom-Up DP)
▶ viz

Fill a table of subproblem answers in an explicit order from base cases upward, with loops instead of recursion.

O(states × transition cost) · O(states), reducible to O(window of dependencies) space
1D (Linear) DP
▶ viz

State is a single index into a sequence; dp[i] is the best answer for the prefix (or suffix) ending at i.

O(n) with O(1) transitions; O(n²) when each state scans all earlier states · O(n), usually reducible to O(1) space
2D (Two-Sequence) DP
▶ viz

State is a pair of prefix lengths (i, j) over two sequences; dp[i][j] combines answers for shorter prefixes of each.

O(n·m) · O(n·m), reducible to O(min(n, m)) space
State Machine DP
▶ viz

State is (position, small status flag); transitions are the edges of a tiny automaton evaluated once per input element.

O(n · k²) for k statuses (O(n · k) when the automaton is sparse) · O(k) space
Grid DP
▶ viz

State is a cell (r, c); the answer for a cell comes from its allowed predecessor cells (usually up and left).

O(rows × cols) · O(rows × cols), reducible to O(cols) space
Knapsack DP
▶ viz

State is (items considered, capacity used); choose items to maximize value or count/decide subsets hitting a target sum.

O(n · W) · O(W) with a rolled row (O(n · W) if reconstruction is needed) space
Subsequence DP
▶ viz

State is "best subsequence ending at index i"; transition scans all earlier j that can precede i.

O(n²) generic; O(n log n) for LIS-type orderings via binary search or Fenwick tree · O(n) space
Interval (Range) DP
▶ viz

State is a contiguous range [l, r]; the answer is built by choosing a split point or the last element removed inside the range.

O(n³) with a split-point transition; O(n²) with an O(1) transition · O(n²) space
Tree DP

State is a node (plus a small flag); each node combines the answers of its children in post-order.

O(n · k) for k statuses per node (O(n) typically); O(n · K²) for subtree-knapsack merges with the small-to-large bound · O(n) table + O(height) recursion space
Bitmask DP
▶ viz

State is a bitmask encoding which of n ≤ ~20 elements are used, plus optionally the last element; transitions add one bit.

O(2^n · n²) for TSP-style (mask, last) states; O(2^n · n) for dp[mask] with one-bit transitions; O(3^n) for submask enumeration · O(2^n · n) or O(2^n) space
Digit DP

Count numbers in [0, N] with a digit property by scanning N's digits with a "tight" flag and a small property state.

O(D × S × B) — D digits (≤ 19), S property states, B base (10) · O(D × S) space
DP on DAGs
▶ viz

State is a vertex; process vertices in topological order so every predecessor is finalized before its successors.

O(V + E) · O(V + E) space
Fibonacci Numbers
▶ viz

Compute F(n) = F(n-1) + F(n-2) in linear time by reusing the two previous values instead of recomputing them.

O(n) · O(1) space
Climbing Stairs
▶ viz

Count the ways to reach step n taking 1 or 2 steps at a time — a Fibonacci recurrence in disguise.

O(n) · O(1) space
0/1 Knapsack
▶ viz

Choose a subset of items, each used at most once, maximizing total value without exceeding a weight capacity.

O(n·W) · O(W) space
Unbounded Knapsack
▶ viz

Maximize value under a capacity when every item may be taken any number of times — the 0/1 loop run forward.

O(n·W) · O(W) space
Coin Change
▶ viz

Find the fewest coins that sum to an amount (or count the ways) using unlimited coins of given denominations.

O(amount · k) · O(amount) space
Longest Increasing Subsequence
▶ viz

Find the length of the longest strictly increasing subsequence — O(n²) DP or O(n log n) with patience sorting.

O(n log n) · O(n) space
Longest Common Subsequence
▶ viz

Find the longest subsequence shared by two sequences using a 2D table over prefix pairs.

O(n·m) · O(min(n, m)) space
Edit Distance
▶ viz

Minimum number of insertions, deletions, and substitutions to turn one string into another via a 2D prefix table.

O(n·m) · O(min(n, m)) space
Matrix Chain Multiplication
▶ viz

Choose the parenthesization of a matrix product that minimizes scalar multiplications — the archetypal interval DP.

O(n³) · O(n²) space
Kadane's Algorithm
▶ viz

Find the maximum-sum contiguous subarray in one pass by tracking the best sum ending at each position.

O(n) · O(1) space
House Robber
▶ viz

Maximize the sum of chosen array elements with no two adjacent — a take-or-skip 1D DP with two rolling variables.

O(n) · O(1) space
Graph Algorithms

Traversal, shortest paths, spanning trees, connectivity and DAG ordering.

All 23 →
Breadth-First Search (BFS)
▶ viz

Explore a graph layer by layer from a source using a FIFO queue, visiting every node at distance d before any node at distance d + 1.

O(V + E) · O(V) space
Depth-First Search (DFS)
▶ viz

Explore a graph by following one path as deep as possible before backtracking, using recursion or an explicit stack.

O(V + E) · O(V) space
BFS Shortest Path (Unweighted)
▶ viz

Shortest path in an unweighted graph: BFS from the source, record parents, then walk parents back from the target to reconstruct the path.

O(V + E) · O(V) space
Dijkstra's Algorithm
▶ viz

Single-source shortest paths on graphs with non-negative edge weights, greedily settling the closest unsettled node using a min-priority queue.

O((V + E) log V) · O(V + E) space
Bellman-Ford
▶ viz

Single-source shortest paths that tolerate negative edge weights: relax every edge V - 1 times, then one more pass to detect negative cycles.

O(V · E) · O(V) space
Floyd-Warshall
▶ viz

All-pairs shortest paths by dynamic programming over the set of allowed intermediate nodes: three nested loops, O(V³), handles negative edges.

O(V³) · O(V²) space
0-1 BFS
▶ viz

Shortest paths when every edge weighs 0 or 1: a deque replaces the heap — weight-0 edges push to the front, weight-1 edges to the back — giving O(V + E).

O(V + E) · O(V) space
A* Search
▶ viz

Point-to-point shortest path that steers Dijkstra toward the goal with a heuristic h(v): pop by f = g + h; optimal when h never overestimates.

O((V + E) log V) · O(V) space
Prim's Algorithm
▶ viz

Minimum spanning tree by growing one tree from a start node, always adding the cheapest edge that crosses from the tree to a new node.

O(E log V) · O(V + E) space
Kruskal's Algorithm
▶ viz

Minimum spanning tree by sorting all edges and greedily adding each edge that joins two different components, tracked with union-find.

O(E log E) · O(V + E) space
Connected Components
▶ viz

Partition an undirected graph into maximal groups of mutually reachable vertices with one traversal per group.

O(V + E) · O(V) space
Strongly Connected Components
▶ viz

Maximal vertex sets of a directed graph in which every vertex can reach every other; computed in linear time by Tarjan or Kosaraju.

O(V + E) · O(V + E) space
Tarjan's SCC Algorithm
▶ viz

Find all strongly connected components in one DFS using discovery indices, low-link values and an explicit stack.

O(V + E) · O(V) space
Kosaraju's Algorithm
▶ viz

Find strongly connected components with two DFS passes: record finish order, then DFS the reversed graph in decreasing finish time.

O(V + E) · O(V + E) space
Topological Sort
▶ viz

Order the vertices of a directed acyclic graph so that every edge points forward; exists iff the graph has no cycle.

O(V + E) · O(V) space
Kahn's Algorithm
▶ viz

Topologically sort a DAG by repeatedly emitting vertices whose in-degree has dropped to zero; leftover vertices reveal a cycle.

O(V + E) · O(V) space
DFS Topological Sort
▶ viz

Run DFS, record vertices as they finish, and reverse that list; a grey-to-grey edge during the search means a cycle.

O(V + E) · O(V) space
Cycle Detection
▶ viz

Decide whether a graph has a cycle: three-colour DFS for directed graphs; DFS with parent tracking or union-find for undirected graphs.

O(V + E) · O(V) space
Bipartite Check
▶ viz

Colour vertices with two colours so every edge joins different colours; succeeds iff the graph has no odd cycle.

O(V + E) · O(V) space
Bridges
▶ viz

Find every edge of an undirected graph whose removal disconnects it, using DFS discovery times and low-link values.

O(V + E) · O(V + E) space
Articulation Points
▶ viz

Find every vertex of an undirected graph whose removal disconnects it, via DFS low-link values with a special rule for the root.

O(V + E) · O(V) space
Eulerian Path
▶ viz

A walk that uses every edge exactly once; exists under simple degree conditions and is built greedily by Hierholzer's algorithm in O(E).

O(V + E) · O(V + E) space
Eulerian Circuit
▶ viz

A closed walk using every edge exactly once; exists iff the graph is connected on its edges and every vertex is balanced.

O(V + E) · O(V + E) space
String Algorithms

Pattern matching, hashing, palindromes and suffix structures.

All 9 →
Naive String Matching
▶ viz

Try every alignment of the pattern against the text and compare character by character.

O(n · m) · O(1) space
Knuth–Morris–Pratt (KMP)
▶ viz

Linear-time pattern matching that never re-reads text characters, using a precomputed failure (LPS) table of the pattern.

O(n + m) · O(m) space
Rabin–Karp
▶ viz

Compare a rolling hash of each text window with the pattern hash and verify only on hash hits.

O(n · m) · O(1) space
Z-Algorithm
▶ viz

Compute for every position the length of the longest substring starting there that matches a prefix of the string, in linear time.

O(n + m) · O(n + m) space
Manacher's Algorithm
▶ viz

Compute the palindrome radius around every center in O(n) by reusing mirrored radii inside the rightmost known palindrome.

O(n) · O(n) space
Rolling Hash (Polynomial Hashing)
▶ viz

Precompute prefix hashes so the hash of any substring — and hence substring equality — can be evaluated in O(1).

O(n) · O(n) space
Aho–Corasick
▶ viz

Search a text for every word of a dictionary simultaneously by walking a trie augmented with KMP-style failure links.

O(n + L + z) · O(L · σ) space
Suffix Array

Sort all suffixes of a string by index; with the LCP array it answers substring search, distinct-substring counts and longest-repeat queries.

O(n log² n) · O(n) space
Suffix Tree

A compressed trie of all suffixes of a string; answers substring search in O(m), longest repeat and distinct-substring counts directly from its structure.

O(n) · O(n · σ) space
Bit Manipulation

Operators, masks, tricks and subset enumeration.

All 7 →
Mathematical Algorithms

GCD, primes, fast exponentiation, modular arithmetic and combinatorics.

All 8 →