⚡ Competitive Programming

A progressive journey from absolute beginner to advanced competitor

Every chapter builds on the last. You'll start by reading input and writing output, then progress through loops, arrays, sorting, recursion, dynamic programming, graphs, and advanced techniques — all the way to grandmaster-level problem solving.

Code examples in C++ and Rust throughout each chapter.

Phase 1: The Absolute Basics

Chapter 1

Reading Input and Writing Output

stdin, stdout, multiple test cases — the foundation of every solution.

Chapter 2

Your First Loop

while and for loops, summation, counting, and accumulation patterns.

Chapter 3

Conditionals and Decision Making

if/else, logical operators, ternary expressions — making decisions in code.

Chapter 4

Storing Data with Arrays

Indexing, iteration, vectors — storing collections of data.

Chapter 5

Strings and Characters

Strings as character arrays, reading, reversing, counting characters.

Chapter 6

Functions to Organize Code

Parameters, return values, reusability — breaking code into named blocks.

Chapter 7

Refactoring: Cleaner Functions

Single-responsibility, extracting helpers, naming — writing readable code.

Chapter 8

Debugging Your First Errors

Off-by-one, print debugging, compiler errors, common pitfalls.

Chapter 9

Counting and Summation Patterns

Running totals, frequency counters, conditional counting.

Chapter 10

Finding Maximum and Minimum

Manual min/max, built-in helpers, single-pass both-at-once.

Phase 2: Thinking Algorithmically

Chapter 11

Searching Through Arrays

Linear search, find first occurrence, count occurrences.

Chapter 12

Refactoring: Early Exits and Guard Clauses

Replacing nested ifs with early returns for cleaner code.

Chapter 13

Sorting: Bubble and Selection

Understanding O(N²) sorts — and why you'll rarely write them.

Chapter 14

Refactoring: Using Built-in Sort

One-liner sort with custom comparators. O(N log N).

Chapter 15

Two Pointer Technique

Pair sum, remove duplicates — O(N²) → O(N) with two indices.

Chapter 16

Sliding Window Basics

Fixed and variable-size windows for O(N) subarray problems.

Chapter 17

Refactoring: Window Shrinking Patterns

Extracting the shrink-while loop into a reusable helper.

Phase 3: Number Theory and Math

Chapter 18

Prime Numbers: The Naive Way

Trial division, √N optimisation — checking primality.

Chapter 19

Refactoring: Sieve of Eratosthenes

O(N log log N) sieve for finding all primes up to N.

Chapter 20

Greatest Common Divisor

Euclidean algorithm — O(log min(a,b)).

Chapter 21

Least Common Multiple

LCM from GCD, avoiding overflow, array LCM.

Chapter 22

Modular Arithmetic Basics

Add, multiply, subtract modulo M. Why 10⁹+7.

Chapter 23

Fast Exponentiation

Binary exponentiation — O(log b) instead of O(b).

Chapter 24

Refactoring: Binary Exponentiation

Generic template, recursive vs iterative approaches.

Chapter 25

Factorials and Combinatorics

nCr via modular inverses and Fermat's little theorem.

Chapter 26

Refactoring: Precomputing Factorials

O(1) nCr with precomputed fact & inv_fact arrays.

Phase 4: Data Structures

Chapter 27

Dynamic Arrays (Vectors/Lists)

Dynamic resizing, push_back, reserve — your default array type.

Chapter 28

Stacks: Undo and Backtracking

LIFO data structure, push/pop/top, balanced parentheses.

Chapter 29

Refactoring: Stack for Parentheses

Counter vs stack for multiple bracket types, index stacks.

Chapter 30

Queues and Fair Processing

FIFO, deque, and a preview of BFS on grids.

Chapter 31

Maps and Dictionaries

Key-value stores, unordered_map, HashMap, ordered vs unordered.

Chapter 32

Refactoring: Frequency Counting

O(N²) nested loops → O(N) hash map — anagram checking.

Chapter 33

Sets for Unique Items

Uniqueness, HashSet, unordered_set, duplicate detection.

Chapter 34

Priority Queues and Heaps

Max-heap, min-heap, top K elements pattern.

Chapter 35

Refactoring: Running Median

O(N²) insert-and-shift → O(N log N) two-heap streaming median.

Phase 5: Recursion and Backtracking

Chapter 36

Thinking Recursively

Base cases, stack frames, and the recursive leap of faith.

Chapter 37

Factorial and Fibonacci Recursively

Linear recursion vs tree recursion — O(N) vs O(2^N).

Chapter 38

Refactoring: Memoization

Caching recursive results: O(2^N) Fibonacci → O(N).

Chapter 39

Generating All Subsets

Include/exclude decision tree and the power set.

Chapter 40

Refactoring: Bitmask Subsets

Recursive subsets → iterative bitmask enumeration (2^N loop).

Chapter 41

Permutations and Combinations

N! permutations, C(N,K) combinations, next_permutation.

Chapter 42

N-Queens and Backtracking

Classic backtracking: row-by-row placement with O(1) conflict checks.

Chapter 43

Refactoring: Pruning Search Space

O(N) scan → O(1) boolean array lookup. Symmetry and forward checking.

Phase 6: Greedy Algorithms

Chapter 44

The Greedy Mindset

Local vs global optima, when greedy works, and the coin change example.

Chapter 45

Activity Selection Problem

Sort by finish time, greedily pick non-overlapping activities.

Chapter 46

Refactoring: Interval Scheduling

Brute force O(N×2^N) → greedy O(N log N) interval scheduling.

Chapter 47

Fractional Knapsack

Sort by value/weight ratio, take as much of the best as you can.

Chapter 48

Huffman Coding Basics

Prefix-free codes, merge the two smallest frequencies greedily.

Chapter 49

Refactoring: Priority Queue Huffman

O(N²) linear scan → O(N log N) min-heap Huffman merge.

Phase 7: Dynamic Programming

Chapter 50

What is Dynamic Programming

Optimal substructure, overlapping subproblems, top-down vs bottom-up.

Chapter 51

Fibonacci with DP

Memoisation vs tabulation — O(2^N) to O(N).

Chapter 52

Space Optimized DP

O(N) array → O(1) rolling variables for linear DP.

Chapter 53

Climbing Stairs

Fibonacci in disguise — counting ways with 1 or 2 steps.

Chapter 54

0/1 Knapsack Problem

Take or leave each item — classic 2D DP with recurrence.

Chapter 55

1D Knapsack

O(N×W) memory → O(W) with backward capacity iteration.

Chapter 56

Longest Common Subsequence

2D DP for string comparison — match extends, mismatch skips.

Chapter 57

LCS Space Optimization

O(N×M) → O(M) memory with two-row rolling technique.

Chapter 58

Edit Distance

Levenshtein distance — insert, delete, replace operations.

Chapter 59

Coin Change

Unbounded knapsack — minimum coins and counting ways.

Chapter 60

Bottom-up vs Top-down DP

Choosing between memoisation and tabulation in contests.

Chapter 61

Grid Paths

2D grid DP — from above + from left, obstacles, space optimisation.

Chapter 62

DP on Trees

DFS post-order DP — subtree properties computed bottom-up.

Chapter 63

Digit DP

Counting numbers with properties in a range using the tight flag.

Chapter 64

State Compression DP

Bitmask DP for TSP — O(N² × 2^N) set-DP template.

Phase 8: Graph Theory

Chapter 65

Adjacency List

O(V+E) graph representation — the standard for sparse graphs.

Chapter 66

Adjacency Matrix

O(V²) representation — O(1) edge queries for dense graphs.

Chapter 67

Choosing Representation

When to use list vs matrix — decision framework with conversion.

Chapter 68

Depth First Search

Recursive and iterative DFS — O(V+E) graph exploration.

Chapter 69

Breadth First Search

Queue-based level-order traversal and shortest path in unweighted graphs.

Chapter 70

Connected Components

DFS from each unvisited node — find and label components.

Chapter 71

Union-Find (DSU)

Near-O(1) dynamic connectivity with path compression.

Chapter 72

Dijkstra's Algorithm

Shortest path — O(V²) naive version for dense graphs.

Chapter 73

Dijkstra with Priority Queue

O((V+E) log V) — the standard Dijkstra for sparse graphs.

Chapter 74

Bellman-Ford

Shortest paths with negative edges and cycle detection.

Chapter 75

DAG Shortest Path

O(V+E) shortest path using topological order — no heap needed.

Chapter 76

Kruskal's MST

Sort edges by weight, add non-cycle edges.

Chapter 77

Kruskal with Union-Find

O(E log V) MST — DSU makes cycle check near-O(1).

Chapter 78

Prim's MST

Grow the tree with a priority queue — O((V+E) log V).

Chapter 79

Topological Sort

Kahn's algorithm — O(V+E) DAG ordering with cycle detection.

Chapter 80

Kosaraju's SCC

Two-pass DFS for strongly connected components.

Chapter 81

Tarjan's SCC

Single-pass SCC with low-link values and a stack.

Phase 9: Advanced Techniques

Chapter 82

Binary Search on Arrays

O(log N) search on sorted arrays — the classic divide-and-conquer.

Chapter 83

Lower and Upper Bound

C++ lower_bound/upper_bound and Rust partition_point.

Chapter 84

Binary Search on Answer

Search the solution space with monotonic predicates.

Chapter 85

Ternary Search

Finding max/min of unimodal functions in O(log range).

Chapter 86

Meet in the Middle

2^N → 2 × 2^(N/2) — subset sum for N ≤ 40.

Chapter 87

Bit Manipulation Tricks

Essential bit tricks — LSB, popcount, power-of-two check.

Chapter 88

Bit Subset Enumeration

sub = (sub-1) & mask — enumerate subsets of a bitmask.

Chapter 89

Inclusion-Exclusion

Count unions with bitmask — add odd subsets, subtract even.

Chapter 90

Matrix Exponentiation

O(K³ log N) linear recurrences — Fibonacci for N=10¹⁸.

Chapter 91

Fast Matrix Power

Cache-friendly i-k-j loops and zero-skip optimisations.

Chapter 92

Sqrt Decomposition

O(√N) range queries with blocks of size √N.

Chapter 93

Mo's Algorithm

Offline range queries in O((N+Q)√N).

Phase 10: Trees & Advanced Structures

Chapter 94

Tree Traversals

DFS pre/post-order — the foundation of all tree algorithms.

Chapter 95

Binary Search Trees

BST properties and using std::set/map as ordered containers.

Chapter 96

Lowest Common Ancestor

Finding LCA with naive walk-up — O(N) per query.

Chapter 97

LCA Binary Lifting

O(N log N) preprocess, O(log N) LCA queries.

Chapter 98

Segment Tree

O(log N) range queries and point updates.

Chapter 99

Lazy Propagation

O(log N) range updates with deferred propagation.

Chapter 100

Fenwick Tree

O(log N) prefix sums — simpler and faster than segment tree.

Chapter 101

Range Updates with BIT

Two BITs for O(log N) range update + range query.

Chapter 102

Trie

Prefix tree — O(L) string search and prefix queries.

Chapter 103

Suffix Array & LCP

Sorted suffixes for pattern matching and stringology.

Chapter 104

Heavy Light Decomposition

Path queries in O(log² N) using heavy path decomposition.

Phase 11: Strings & Pattern Matching

Chapter 105

KMP Pattern Matching

O(N+M) string matching with the LPS prefix function.

Chapter 106

Z-Algorithm

O(N) pattern matching via Z-array on concatenated string.

Chapter 107

Rabin-Karp Rolling Hash

O(N+M) average string matching with rolling hash.

Chapter 108

Double Hashing

Eliminating hash collisions with two moduli.

Chapter 109

Manacher's Algorithm

O(N) longest palindromic substring — all radii at once.

Chapter 110

Aho-Corasick

Multi-pattern matching — trie + KMP failure links.

Phase 12: Network Flow & Matching

Chapter 111

Ford-Fulkerson

DFS-based max flow with residual graphs.

Chapter 112

Edmonds-Karp

BFS-based Ford-Fulkerson — O(V×E²) max flow.

Chapter 113

Dinic's Algorithm

The standard max flow — level graph + blocking flow.

Chapter 114

Min-Cut Max-Flow

Max flow = min cut. Finding the cut from residual graph.

Chapter 115

Bipartite Matching

Kuhn's DFS augmenting paths — O(V×E) matching.

Chapter 116

Hopcroft-Karp

O(E√V) bipartite matching with BFS + DFS phases.

Phase 13: Computational Geometry

Chapter 117

Points, Lines & Vectors

Dot product, cross product, orientation — geometry primitives.

Chapter 118

Graham Scan

Convex hull via polar angle sorting.

Chapter 119

Monotone Chain

Andrew's algorithm — integer-only convex hull.

Chapter 120

Line Intersection

Checking segment intersection with orientation tests.

Chapter 121

Point in Polygon

Ray casting — O(N) point-in-polygon test.

Chapter 122

Closest Pair

O(N log N) divide-and-conquer closest pair of points.

Chapter 123

Sweep Line

Plane sweep paradigm for geometric intersection problems.

Phase 14: Number Theory Advanced

Chapter 124

Euler's Totient

φ(n) = count of coprimes ≤ n — O(√N) computation.

Chapter 125

Totient Sieve

All φ(1..N) in O(N log log N).

Chapter 126

Modular Inverse

Fermat (prime M) and extended Euclidean (any M).

Chapter 127

Chinese Remainder Theorem

Solving systems of congruences with coprime moduli.

Chapter 128

Garner's Algorithm

Incremental CRT avoiding large intermediate products.

Chapter 129

Möbius Function

Multiplicative function for divisibility inclusion-exclusion.

Chapter 130

NTT & Polynomials

FFT over finite fields — O(N log N) polynomial multiplication.

Phase 15: Game Theory & Misc

Chapter 131

Nim Games

XOR of pile sizes determines the winner.

Chapter 132

Sprague-Grundy Theorem

Every impartial game = Nim heap. mex of reachable states.

Chapter 133

Memoized Grundy

Top-down Grundy computation for sparse state spaces.

Chapter 134

Expected Value

Linearity of expectation and indicator random variables.

Chapter 135

Monte Carlo Simulation

Estimating values through random sampling.

Chapter 136

Importance Sampling

Variance reduction by sampling from skewed distributions.

Phase 16: Contest Strategy & Mastery

Chapter 137

Reading Problems Fast

Extracting the core problem in 30 seconds.

Chapter 138

Estimating Time Complexity

Constraint → algorithm guide — which O matches which N.

Chapter 139

Complexity Checklist

Pre-submission checklist to catch TLE/MLE/WA bugs.

Chapter 140

Stress Testing

Random test generation with brute-force comparison.

Chapter 141

Common Bug Patterns

Top 5 bugs — off-by-one, overflow, uninitialised, modulo, reset.

Chapter 142

Defensive Coding

Writing code that prevents bugs with assertions and safe patterns.

Chapter 143

Code Templates

Building a lean contest template — I/O, aliases, debug helpers.

Chapter 144

Time Pressure

Time management — problem order and the 20-minute rule.

Chapter 145

Team Strategy

ICPC roles — reader, thinker, coder. Communication is everything.

Chapter 146

Grandmaster Problems

Combining techniques — the mindset for advanced problem solving.


16 phases · 146 chapters · From zero to grandmaster

Built with Tailwind CSS · Edited in LazyVim on macOS