Skip to content

Chapter 16: Competitive Programming

This book covers algorithmic problem-solving beyond standard interview preparation: the speed and depth needed for ICPC, Codeforces, and quantitative trading interviews. It is a guided companion to a free textbook and a curated problem set rather than a set of chapters of its own. For each topic it tells you what to read, which ideas matter, which problems to solve first, and where the topic connects to the rest of the library.

Concepts from other sections (21)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

  • Fermat’s little theorem: if pp is prime and does not divide aa, then ap−1≡1(modp)a^{p-1} \equiv 1 \pmod p; it reduces large exponents modulo p−1p - 1 and underlies primality tests and RSA. Read more: Chapter 12: Discrete Math 2 in Mathematics
  • Euclidean algorithm / extended Euclidean algorithm: computes gcd⁡(a,b)\gcd(a, b) by repeating gcd⁡(a,b)=gcd⁡(b,a mod b)\gcd(a, b) = \gcd(b, a \bmod b) until the remainder is 0; the extended version also returns x,yx, y with ax+by=gcd⁡(a,b)ax + by = \gcd(a, b), which gives modular inverses. Read more: Chapter 12: Discrete Math 2 in Mathematics
  • Bezout’s identity: for any integers aa and bb there are integers xx and yy with ax+by=gcd⁡(a,b)ax + by = \gcd(a, b); the extended Euclidean algorithm finds them. Read more: Chapter 12: Discrete Math 2 in Mathematics
  • RSA: a public-key cryptosystem with modulus n=pqn = pq for primes p,qp, q, public exponent ee, and private exponent d=e−1 mod (p−1)(q−1)d = e^{-1} \bmod (p-1)(q-1); encryption is me mod nm^e \bmod n and decryption cd mod nc^d \bmod n, and its security rests on the difficulty of factoring nn. Read more: Chapter 12: Discrete Math 2 in Mathematics
  • Greatest common divisor (GCD): gcd⁡(a,b)\gcd(a, b), the largest integer dividing both aa and bb; aa has a multiplicative inverse modulo nn exactly when gcd⁡(a,n)=1\gcd(a, n) = 1. Read more: Chapter 12: Discrete Math 2 in Mathematics
  • Union-find / disjoint-set union (DSU): a forest that keeps elements in disjoint sets, with find returning a set’s root and union merging two sets; it answers “are these connected?” as edges arrive in nearly constant amortized time per operation. Read more: Chapter 8: Graphs
  • Prefix sum: the running total of an array up to each position, so any subarray sum is the difference of two prefix sums; with a hash map of the prefix sums seen so far, it counts the subarrays that sum to kk in O(n)O(n). Read more: Chapter 3: Arrays and hashing
  • Interval scheduling: selecting the most non-overlapping intervals, solved greedily by sorting on end time and taking each interval that starts no earlier than the last chosen one ends. Read more: Chapter 10: Greedy algorithms
  • Double hashing: generating probes gi=h1+i h2g_i = h_1 + i\,h_2 from two hashes. Read more: 15.8 A Bloom filter
  • Trie: a rooted tree whose edges carry characters so that each node spells the string on its path. Read more: 12.2 Trees and tries, longest-prefix match in Mathematics
  • DAG: a directed graph with no directed cycle. Read more: 12.1 Graphs, DAGs, and an iterative topological sort in Mathematics
  • Cross product: for vectors in 3D, u×vu \times v is perpendicular to both, with magnitude ∥u∥∥v∥sin⁡θ\lVert u \rVert \lVert v \rVert \sin\theta, the area of the parallelogram they span; it gives normals to planes. Read more: Chapter 10: Calculus 3 in Mathematics
  • Closest pair of points: finding the two nearest points in the plane in O(nlog⁡n)O(n \log n) by splitting on xx, solving each half, and checking only a strip around the dividing line, where each point needs comparing with a constant number of others. Read more: Chapter 13: Recursion and divide-and-conquer
  • Divide and conquer / divide-and-conquer: an algorithm design that splits a problem into independent subproblems, solves them recursively, and combines their results; unlike dynamic programming the subproblems do not overlap, and the gain comes from better asymptotics, as in merge sort. Read more: Chapter 13: Recursion and divide-and-conquer
  • Dynamic programming (DP): solving a problem by breaking it into overlapping subproblems and storing each subproblem’s answer the first time it is computed, which turns an exponential recursion into a polynomial computation. Read more: Chapter 9: Dynamic programming
  • Bitmask DP: dynamic programming whose state includes a subset of up to about 20 items encoded as the bits of an integer, giving 2n2^n states; used for the Travelling Salesman Problem and subset partitioning. Read more: Chapter 9: Dynamic programming
  • Generating function: the power series A(x)=∑anxnA(x) = \sum a_n x^n whose coefficients are a sequence; algebra on A(x)A(x) solves counting problems and recurrences. Read more: Chapter 12: Discrete Math 2 in Mathematics
  • Breadth-first search (BFS): traversal in order of hop distance using a FIFO queue. Read more: 18.6 Graph as an adjacency list
  • Depth-first search (DFS): traversal that follows one path as far as possible before backtracking, using a stack. Read more: 18.6 Graph as an adjacency list
  • Binary search: a search that keeps an interval known to contain the answer and halves it with one comparison per step, taking O(log⁡n)O(\log n) steps; it needs a monotonic predicate, not necessarily a sorted array. Read more: Chapter 5: Binary search
  • HRT: humility, respect, and trust, the book’s model for how engineers should work together. Read more: Chapter 2: Software Engineering at Google in Software Engineering

It is written for readers who have finished the fundamentals and want to go further. Competitive programming demands both correctness and speed: O(n log n) is not always enough, and constant factors matter. Most hard problems combine two or three known techniques, and the skill is recognizing which ones. Implementation speed comes from having templates and patterns internalized, not from typing fast, and the gap between knowing an algorithm and solving a problem with it is pattern recognition. By the end you will be able to identify the structure of a hard problem, pick the right technique, and implement it cleanly under time pressure.

Every competitive programming problem reduces to three steps: identify the mathematical structure, pick the right data structure, and implement it cleanly in under 30 minutes. The topics below are the structures and techniques that appear most often in hard problems and quant interviews, and that are rarely covered in interview preparation.

You should be comfortable with the material in Programming and Algorithms, especially its first eleven chapters. The primary textbook is Antti Laaksonen’s Competitive Programmer’s Handbook, available as a free PDF. The problems come from the CSES Problem Set, 300 curated problems, with harder practice on Codeforces and AtCoder.

Work through the CSES Problem Set in order; it is deliberately sequenced. Read the handbook chapter for a topic before attempting problems in that category. Time yourself, starting at 30 minutes per problem and working down to 15 as you improve. And upsolve every problem you cannot solve: read the editorial, implement the solution, then solve it again from scratch a week later. Practice continues well after the last topic.

Handbook chapters 21 and 22 cover the number theory that contest problems lean on. Modular arithmetic comes first: operations under a modulus, and the modular inverse via Fermat’s little theorem, ap−2 mod pa^{p-2} \bmod p. The sieve of Eratosthenes generates primes in O(nlog⁡log⁡n)O(n \log \log n), and a linear sieve computes multiplicative functions. The extended Euclidean algorithm solves ax+by=gcd⁡(a,b)ax + by = \gcd(a, b), which is Bezout’s identity. The Chinese remainder theorem solves systems of modular equations, and Euler’s totient counts coprime integers, with RSA as its best-known application.

Start with the CSES problems Exponentiation, Counting Divisors, Common Divisors, and Sum of Divisors. For a challenge, try Necklace of Beads and GCD Table on Codeforces. The theory behind this topic is Discrete math 2 in Mathematics, and the same ideas reach into cryptography and quant interview puzzles.

Handbook chapters 15 to 20 cover graphs beyond traversal. For shortest paths, Dijkstra handles non-negative weights, Bellman-Ford handles negative edges, Floyd-Warshall computes all pairs, and SPFA is a queue-based variant of Bellman-Ford. Minimum spanning trees come from Kruskal’s algorithm with union-find or Prim’s with a priority queue. Strongly connected components come from Kosaraju’s or Tarjan’s algorithm, and 2-SAT reduces to them. Network flow runs from Ford-Fulkerson through Edmonds-Karp, O(VE2)O(VE^2), to Dinic’s, O(V2E)O(V^2 E), with the min-cut max-flow theorem tying flows to cuts. Bipartite matching uses the Hungarian algorithm or Hopcroft-Karp, and Euler tours and paths use Hierholzer’s algorithm once their necessary conditions hold.

Start with Shortest Routes I and II, Road Reparation, Planets and Kingdoms, and Download Speed on CSES; the challenge problems are Police Chase, School Dance, and Distinct Routes. The basics are in Graphs, and network flow appears in quant trading in problems of optimal execution.

Handbook chapters 9 and 28 cover range queries. Static queries need only prefix sums, in one or two dimensions, or a sparse table, which answers range-minimum queries in O(1)O(1) after an O(nlog⁡n)O(n \log n) build. A segment tree supports a point update and a range query in O(log⁡n)O(\log n) and builds in O(n)O(n). Lazy propagation extends it to range updates in O(log⁡n)O(\log n) by deferring work, and a persistent segment tree keeps version history at O(log⁡n)O(\log n) per operation. A Fenwick tree (binary indexed tree) is a simpler alternative for prefix operations, with O(log⁡n)O(\log n) update and query, and a merge sort tree answers range order statistics.

Start with Static Range Sum, Dynamic Range Sum, Range Minimum Queries, and Range Update Queries; the challenges are Salary Queries, Prefix Sum Queries, and Pizzeria Queries. The same structures show up in database indexing, computational geometry, and interval scheduling.

Handbook chapter 26 covers strings. Polynomial rolling hashes power Rabin-Karp, and double hashing avoids collisions. KMP uses a failure function to match a pattern in O(n+m)O(n + m), and the Z-algorithm builds a Z-array as an alternative. A trie is a prefix tree, and Aho-Corasick extends it to many patterns at once. A suffix array builds in O(nlog⁡n)O(n \log n) and, with its LCP array, answers substring queries; a suffix automaton is a DAG of all substrings built in O(n)O(n).

Start with String Matching, Finding Borders, Finding Periods, and Minimal Rotation; the challenges are Substring Order I and II and Repeating Substring. The connections run to compression, in Information theory, and to sequence alignment in bioinformatics.

Handbook chapters 29 and 30 cover computational geometry. The cross product is the workhorse: it gives the orientation test (left, right, or collinear) and the area of a triangle or polygon. The convex hull comes from Andrew’s monotone chain in O(nlog⁡n)O(n \log n) or a Graham scan. Line intersection uses a parametric form or a sweep line, the closest pair of points uses divide and conquer in O(nlog⁡n)O(n \log n), and polygon operations include point-in-polygon by ray casting and area by the shoelace formula.

Start with Point Location Test, Line Segment Intersection, Polygon Area, and Convex Hull; the challenges are Point in Polygon and Minimum Euclidean Distance. The vector background is in Calculus 3, and the same methods drive computer graphics and robot path planning.

Handbook chapters 10, 24, and 25 cover dynamic programming beyond the standard patterns. Bitmask DP enumerates subsets for problems such as the Hamiltonian path and the assignment problem, in O(2n⋅n)O(2^n \cdot n). Digit DP counts numbers up to NN that satisfy constraints. DP on trees uses the rerooting technique for problems such as the tree diameter and subtree queries. The convex hull trick, and its Li Chao tree variant, optimizes DPs whose transitions are linear functions. Divide-and-conquer optimization applies when opt[i][j]≤opt[i][j+1]\text{opt}[i][j] \le \text{opt}[i][j+1] and reduces O(kn2)O(kn^2) to O(knlog⁡n)O(kn \log n), and Knuth’s optimization applies when the cost satisfies the quadrangle inequality.

Start with Elevator Rides, Counting Tilings, and Hamiltonian Flights; the challenges are Money Sums, Removal Game, and Two Sets II. The foundations are in Dynamic programming.

Handbook chapter 25 covers games. In Nim, the XOR of the pile sizes determines the winner. The Sprague-Grundy theorem generalizes this: every impartial game is equivalent to a Nim heap whose size is the game’s Grundy value. Minimax gives optimal play in two-player zero-sum games, with alpha-beta pruning to cut the search. And any game can be modeled as a graph, positions as states and moves as edges, in which each position is classified as winning or losing.

Start with Stick Game, Nim Game, Stair Game, and Grundy’s Game; the challenges are Another Game and Nim Game II. The ideas connect to game-playing agents in Reinforcement learning and to quant interview puzzles.

The fast Fourier transform and polynomial arithmetic

Section titled “The fast Fourier transform and polynomial arithmetic”

The handbook treats the FFT among its number-theory applications in chapter 24. The FFT multiplies polynomials in O(nlog⁡n)O(n \log n) through the discrete Fourier transform, using the Cooley-Tukey algorithm. The number-theoretic transform (NTT) is the FFT over a finite field, which keeps the arithmetic exact for integers. Applications include multiplying large numbers, string matching with wildcards, convolution, and evaluating generating functions, and polynomial division uses the modular inverse of a polynomial.

Start with Polynomial Multiplication on CSES, then convolution problems on Codeforces. The FFT connects to signal processing and to Information theory.

The table collects the main techniques with their costs, for quick recall during practice:

TechniqueTime ComplexityWhen to Use
Prefix sumsO(n) build, O(1) queryStatic range sum queries
Segment treeO(n) build, O(log n) opsDynamic range queries with updates
Fenwick treeO(n) build, O(log n) opsSimpler prefix sum with updates
Sparse tableO(n log n) build, O(1) queryStatic RMQ (idempotent operations)
Union-FindO(alpha(n)) per opDynamic connectivity, MST (Kruskal)
KMP/Z-algoO(n + m)Single pattern matching
Suffix arrayO(n log n) buildAll substring queries
FFT/NTTO(n log n)Polynomial multiplication, convolution
Convex hull trickO(n) / O(n log n)DP optimization with linear cost
Sprague-GrundyGame-dependentImpartial combinatorial games

Codeforces ratings give a rough map of what to focus on at each stage:

LevelRating (CF)Focus
Beginner800-1200Implementation, basic math, sorting/searching
Intermediate1200-1600Standard DP, graph BFS/DFS, binary search on answer
Advanced1600-2000Segment trees, advanced DP, number theory
Expert2000-2400Flows, FFT, advanced data structures, geometry
Master2400+Combining techniques, novel reductions, research-level

These skills are tested directly in some interviews. Jane Street asks probability puzzles, game theory, and optimization under constraints at an expert level. Citadel looks for fast algorithms and mathematical problem-solving at an advanced to expert level. Two Sigma asks algorithmic puzzles and data-structure design, and HRT probes low-latency thinking, bit manipulation, and cache-friendly algorithms, both at an advanced level. Google asks hard LeetCode-style problems with DP or graph twists, and DeepMind asks research-flavored algorithm design at an expert level.

  • Segment tree: a binary tree over array ranges in which each node stores an aggregate, such as the sum or minimum, of its range; it supports point updates and range queries in O(log⁡n)O(\log n) after an O(n)O(n) build.
  • Lazy propagation: deferring range updates in a segment tree by storing pending changes at internal nodes and pushing them to the children only when a later operation descends through, which makes range updates O(log⁡n)O(\log n).
  • Fenwick tree / binary indexed tree (BIT): an array-based structure for prefix sums with O(log⁡n)O(\log n) point updates and prefix queries, smaller and simpler than a segment tree.
  • Sparse table: precomputed answers for every range whose length is a power of two, built in O(nlog⁡n)O(n \log n), that answer idempotent range queries such as range minimum in O(1)O(1) on a static array.
  • Knuth-Morris-Pratt algorithm (KMP): string matching in O(n+m)O(n + m) that uses a failure function over the pattern to know, after a mismatch, how far the pattern can shift without re-reading text.
  • Suffix array: the starting positions of a string’s suffixes in sorted order, built in O(nlog⁡n)O(n \log n); with its LCP (longest common prefix) array it answers substring queries.
  • Sprague-Grundy theorem: every impartial game is equivalent to a Nim heap whose size is the game’s Grundy value, so a sum of games is a win for the player to move exactly when the XOR of the Grundy values is nonzero.
  • Number-theoretic transform (NTT): the fast Fourier transform carried out in arithmetic modulo a suitable prime, which multiplies integer polynomials in O(nlog⁡n)O(n \log n) with exact results and no rounding.
  • Convex hull trick: a DP optimization for transitions that minimize or maximize over a set of linear functions, keeping only the lines on their lower or upper envelope so each transition is a fast query.