DSA Course - Complete Textbook

Mastering DSA
Through Patterns

8 parts · 194 chapters · 38k+ practice problems. Each chapter: brute force first, then the insight, then the optimal.

Part I - Arrays & Pointers

17 chapters
1

Two Pointers

Prune half the search space at every step.

14 min
2

Sliding Window

Turn O(n²) subarray loops into O(n) with a moving window.

18 min
3

Binary Search

Eliminate half the search space every step.

16 min
4

Prefix Sum & Difference Array

Precompute prefix sums. Any range query becomes O(1).

14 min
5

Two Sum Family

One element + its complement. HashMap stores what you've seen. O(n) beats O(n²).

16 min
6

Array Manipulation Tricks

Rotate with 3 reverses. Mark visited in-place. Rearrange with index encoding.

14 min
7

Difference Array & Range Updates

Add delta to range [l,r] in O(1). Prefix sum to recover. Sweep line in 1D.

12 min
8

Contribution Technique

Count how many times each element contributes to the answer. Reverse the summation.

14 min
9

Binary Search on Answer

When you can check "is X achievable?" in O(f(n)), find optimal X in O(f(n) log range).

16 min
10

Permutation Patterns

Next permutation, cycle decomposition, inversions, k-th permutation in O(n).

15 min
11

Word Break & String Segmentation

Can we split a string into valid words? DP with trie or set lookup.

15 min
12

Shortest Supersequence & LCS Duality

SCS(s,t) = |s| + |t| - LCS(s,t). Find minimum string containing both as subsequences.

13 min
13

Kadane's Algorithm & Subarray Variants

Max subarray sum in O(n). Circular variant, k disjoint subarrays, submatrix.

15 min
14

Two Pointer — Advanced Patterns

3Sum, 4Sum, remove duplicates, partition. Multiple pointer coordination.

14 min
15

Cyclic Sort & Missing Numbers

Place each number at its correct index. Find missing/duplicate in O(n) O(1).

11 min
16

Array Rotation & Circular Problems

Rotate by k, search in rotated array, circular queue/buffer problems.

12 min
17

Next Permutation & Lexicographic Order

Find next/previous permutation in-place. Kth permutation, all permutations in order.

12 min

Part II - Linked Structures

20 chapters
18

Linked List

Dummy node. Slow/fast pointers. Reverse in-place.

18 min
20

Advanced Tree Structures

Segment tree for range queries. Fenwick for prefix sums. O(log n) both.

20 min
21

Sparse Table & Binary Lifting

Precompute powers of 2. Answer range min/max in O(1).

18 min
22

Segment Tree: Lazy Propagation

Range update in O(log n). Defer the work until you actually need it.

20 min
23

Cycle Detection

Floyd's tortoise and hare. O(n) time, O(1) space. Detects AND finds the cycle.

14 min
24

Tree Construction from Traversals

Preorder[0] = root. Inorder splits left/right. Find the split, recurse.

16 min
25

Lowest Common Ancestor (LCA)

Find common ancestor of two nodes. Binary lifting O(n log n). Euler tour + RMQ O(n).

16 min
26

DSU on Tree (Small-to-Large)

Heavy child inherits parent's data. Light children merged small-to-large. O(n log n).

15 min
27

Tree Diameter & Path Queries

Diameter via two BFS. Rerooting DP for all-root path queries. Longest path in O(n).

14 min
28

Offline LCA (Tarjan's)

Answer all LCA queries in O(n + q) using Union-Find. Process queries offline.

13 min
29

Tree Isomorphism & Canonical Forms

Two trees are isomorphic iff they have the same canonical form. AHU in O(n log n).

13 min
30

Persistent Union-Find (DSU with Rollback)

Undo union operations. Offline dynamic connectivity with O(n log²n).

14 min
31

Binary Lifting

Jump 2^k ancestors in O(log n). LCA, kth ancestor, path queries on trees.

14 min
32

Segment Tree Basics

Point updates and range queries in O(log n). Build, query, update.

14 min
33

Tree Path Problems

Root-to-leaf paths, path sums, max path through any nodes.

13 min
34

Iterative Tree & Graph Traversal

DFS without recursion. Explicit stack for inorder, preorder, postorder, Morris.

13 min
35

BST Operations & Properties

BST insert, delete, validate, floor/ceiling, kth element, convert to/from sorted.

14 min
36

Linked List Reversal Patterns

Reverse full list, reverse k-groups, reverse between positions, copy with random.

13 min
37

Tree Level-Order Variants

BFS tree traversals: zigzag, right side view, level averages, cousins.

12 min
38

Tree DP on General Trees

DP on trees with arbitrary number of children. Subtree properties, rerooting.

14 min

Part III - Hashing & Auxiliary Structures

14 chapters

Part IV - Core Algorithms

41 chapters
53

Dynamic Programming

Overlapping subproblems + optimal substructure = DP.

24 min
54

Backtracking

Try every option. Undo. Move on.

16 min
55

Greedy Algorithms

Make the locally optimal choice. Hope it's globally optimal.

14 min
57

Shortest Path Algorithms

Dijkstra for non-negative weights. Bellman-Ford for negatives. Floyd for all pairs.

22 min
58

Bitmask DP

Subsets as integers. 2^n states where n ≤ 20.

18 min
59

Divide and Conquer

Split. Solve each half. Merge. Repeat until trivial.

18 min
60

Knapsack DP

Iterate backwards for 0/1. Forwards for unbounded. Know the difference.

18 min
61

Advanced Graph: SCC, Bridges & 2-SAT

Tarjan finds everything: SCCs, bridges, articulation points — one DFS.

22 min
62

Bipartite Graphs & Matching

2-colorable = bipartite. BFS/DFS detects it. Matching pairs them up optimally.

16 min
63

Coordinate Compression

Map large values to small ranks. Enables Fenwick/SegTree on value-based problems.

14 min
64

Topological Sort

Order nodes so all edges point forward. BFS (Kahn's) or DFS post-order.

16 min
65

Minimum Spanning Tree

Connect all nodes with minimum total edge weight. Kruskal or Prim.

16 min
66

Network Flow

Max flow = min cut. Dinic's runs in O(V²E). Models matching, assignment, feasibility.

18 min
67

Meet in the Middle

Split problem in half. Enumerate each half independently. Combine in O(n log n).

14 min
68

Convex Hull Trick

Optimize DP with min/max of linear functions. Maintains a convex hull of lines.

16 min
69

Centroid Decomposition

Divide tree at centroid. Every path passes through O(log n) centroids.

16 min
70

Line Sweep

Sweep a line across events. Sort by x, process events with a sorted structure.

16 min
71

2-SAT

Solve boolean formulas with 2-literal clauses in O(V+E) via SCC.

16 min
72

Bridges & Articulation Points

Find critical edges and vertices. DFS with low[] array. O(V+E).

15 min
73

Min-Cost Max-Flow

Find max flow with minimum total cost. SPFA/Bellman-Ford on residual graph.

17 min
74

Circulation & Flow with Lower Bounds

Edge has both minimum and maximum flow. Reduce to standard max-flow via supply/demand.

16 min
75

Bidirectional BFS

BFS from both source and target. Meet in the middle. Reduces O(b^d) to O(b^(d/2)).

13 min
76

A* Search

Dijkstra guided by a heuristic. Finds optimal path faster when heuristic is good.

14 min
77

Difference Constraints

x_j - x_i ≤ w → edge i→j with weight w. SSSP gives feasible solution.

13 min
78

Functional Graphs

Every node has exactly one outgoing edge. Each component = rho (ρ) shape: tail + cycle.

13 min
79

Matching via Maximum Flow

Bipartite matching = max flow in O(E√V). General matching = Blossom algorithm.

16 min
80

Graph Coloring

Assign colors so no adjacent vertices share a color. Greedy gives ≤ Δ+1 colors.

14 min
81

Top-K & Streaming Algorithms

Maintain top-K elements in streams. Heap-based selection, frequency tracking.

14 min
82

Strongly Connected Components

Tarjan's and Kosaraju's algorithms. Condense cycles into DAG of SCCs.

15 min
83

Graph State Space Search

BFS/Dijkstra on augmented states. (node, extra_state) as graph vertices.

14 min
84

Greedy Interval Problems

Activity selection, meeting rooms, interval scheduling. Sort + greedy sweep.

14 min
85

Constructive Algorithms

Build a valid answer from constraints. Greedy construction, invariant maintenance.

13 min
86

Backtracking with Pruning

Prune search space early. Bound functions, symmetry breaking, feasibility checks.

14 min
87

Multi-Source BFS & 0-1 BFS

BFS from multiple sources simultaneously. 0-1 BFS with deque for mixed weights.

12 min
88

Grid Island Problems

Connected components in grids. BFS/DFS flood fill, area, perimeter, enclosure.

13 min
89

Bellman-Ford & Negative Cycles

Shortest paths with negative edges. Detect negative cycles. SPFA optimization.

13 min
90

Jump Game Variants

Reachability and minimum jumps. BFS, greedy, DP on jump range problems.

13 min
91

Union-Find Applications

Connect components dynamically. Detect cycles, count components, earliest connection.

13 min
92

Greedy String Problems

Remove k digits, largest number, reorganize string. Monotone stack for ordering.

13 min
93

Graph Coloring & Bipartite Checking

Two-color graphs to find odd cycles. Divide into two groups satisfying constraints.

12 min
94

Floyd-Warshall All-Pairs Shortest Paths

O(V³) all-pairs shortest paths. Transitive closure, detect negative cycles.

12 min

Part V - Strings, Sequences & Grid

18 chapters
95

String Algorithms

KMP, Z-algo, rolling hash — pattern matching in O(n).

20 min
96

String Matching Algorithms

KMP: O(n+m) search using failure function. Rabin-Karp: hash-based. Z-algorithm: substring in O(n).

20 min
97

Sequences — LIS, LCS & More

LIS in O(n log n). LCS from DP. Every sequence has a structure.

18 min
98

Matrix & Shape Problems

Spiral traversal, rotation, 2D prefix sums — grids have patterns.

16 min
99

String DP

dp[i][j] = answer for s1[0..i-1] and s2[0..j-1]. Match or skip.

20 min
100

Palindrome Patterns

Expand from center, or DP on intervals. Two approaches cover every palindrome problem.

16 min
101

String Hashing & Rolling Hash

Compare substrings in O(1) after O(n) preprocessing. Rabin-Karp for pattern matching.

14 min
102

Suffix Array & LCP Array

Sort all suffixes. Build LCP array. Enables O(n log n) solutions for hard string problems.

16 min
103

Aho-Corasick Automaton

Multi-pattern string matching in O(n + m + k). KMP generalized to many patterns.

16 min
104

Z-Function & String Matching

z[i] = length of longest string starting at i that matches a prefix. O(n) pattern matching.

13 min
105

Manacher's Algorithm

Find all palindromic substrings in O(n). Extends each palindrome using previous results.

14 min
106

Suffix Automaton (SAM)

Compact structure for all substrings. O(n) build. All substring queries in O(n).

18 min
107

Palindrome Automaton (Eertree)

Build all distinct palindromic substrings in O(n). Count occurrences in O(n).

16 min
108

String Rotations & Booth's Algorithm

Lexicographically minimum rotation in O(n). Check rotation in O(n) via concatenation.

12 min
109

Lyndon Factorization

Every string = unique product of decreasing Lyndon words. Duval's algorithm O(n).

12 min
110

String Construction & Transformation

Build target strings via DP. Edit distance, word ladder, minimum operations.

15 min
111

String Decode & Transform Patterns

Decode encoded strings, run-length encoding, parenthesis-based nesting.

12 min
112

String Parsing & Integer Conversion

atoi, add binary/strings, multiply strings, number to/from base.

11 min

Part VI - Math & Discrete

27 chapters
113

Math & Number Theory

GCD, primes, modular arithmetic — the engine behind CP.

20 min
114

Bit Manipulation

XOR is your best friend. Masks are your toolkit.

15 min
115

Combinatorics & Counting

nCr, inclusion-exclusion, Catalan numbers — count without listing.

16 min
116

Game Theory — Nim & Sprague-Grundy

XOR determines the winner. Grundy values generalize everything.

14 min
117

Computational Geometry

Cross products determine orientation. Convex hull wraps everything.

16 min
118

Number Theory

GCD, primes, modular arithmetic — the math behind the tricks.

20 min
119

Probability & Expected Value DP

E[X] = Σ p(outcome) × value(outcome). DP builds it up iteratively.

16 min
120

Ternary Search

Find minimum of unimodal function in O(log n). Divide range into thirds.

12 min
121

FFT & Polynomial Multiplication

Multiply polynomials in O(n log n). Convolution. Count pairs summing to k.

18 min
122

Sprague-Grundy Theorem

Every impartial game = Nim pile. Grundy value = mex of reachable states.

15 min
123

Chinese Remainder Theorem

Solve x ≡ a1 (mod m1), x ≡ a2 (mod m2), ... in one shot. Extended Euclidean key.

14 min
124

Convex Hull

Smallest convex polygon enclosing all points. Graham scan O(n log n). Andrew's monotone chain.

14 min
125

Inclusion-Exclusion Principle

|A∪B| = |A| + |B| - |A∩B|. Generalize to n sets. Count with constraints.

14 min
126

Catalan Numbers

C(n) counts balanced parentheses, BST shapes, polygon triangulations, and more.

13 min
127

Josephus Problem & Circular Elimination

n people in a circle, every k-th eliminated. Find survivor's position in O(n).

12 min
128

Sieve Variants & Multiplicative Functions

Linear sieve, Euler's totient sieve, Möbius function. Each number factored once.

15 min
129

Burnside's Lemma

Count distinct objects under symmetry. Average fixed points over group actions.

14 min
130

Gray Code & Bit Tricks

Adjacent Gray codes differ by one bit. Bit tricks: lowbit, popcount, bit pairs.

13 min
131

Gaussian Elimination over GF(2)

Solve XOR linear systems. Find XOR basis rank. Determine reachability by XOR.

14 min
132

Lucas Theorem & Combinatorics Mod p

C(n,k) mod prime p in O(log_p n). Pascal mod p has fractal structure.

14 min
133

Lattice Paths & Ballot Problems

Count paths on a grid with constraints. Reflection principle. Catalan structures.

13 min
134

Advanced Counting DP

Partition numbers, Bell numbers, Stirling numbers. DP on combinatorial structures.

15 min
135

Rotating Calipers & Convex Polygon Queries

Farthest pair, diameter, closest parallel edges in O(n) after O(n log n) hull.

14 min
136

Carry & Digit Manipulation DP

DP tracking carries in arithmetic operations. Count valid assignments with constraints.

14 min
137

Random Walk & Expected Value

Expected number of steps in random processes. Linear system or DP on states.

13 min
138

Number Manipulation Tricks

Reverse digits, Roman numerals, palindrome numbers, Excel column mapping.

11 min
139

Bit Counting & Manipulation Tricks

Count set bits, Hamming distance, Brian Kernighan's trick, DP counting bits.

11 min

Part VII - Advanced Topics

13 chapters

Part VIII - Cross-Topic Deep Dives

42 chapters
153

BFS vs DFS — When to Use Each

Shortest path → BFS. Connected components → DFS. Know which in 10 seconds.

20 min
154

Interval Problems — The Complete Guide

Sort by start. Merge overlaps. Sweep with a heap. All interval problems reduce to three patterns.

22 min
155

DP on Trees

Postorder + return value = tree DP. Same template solves diameter, max path, subtree counts.

18 min
156

Union-Find (Disjoint Set Union)

Find the root. Union the sets. Near-constant time with path compression.

16 min
157

Digit DP

Count integers in [0, N] satisfying a digit property.

18 min
158

Interval DP

dp[i][j] = best answer for subproblem on range [i..j].

18 min
159

Grid DP

dp[i][j] depends on neighbors. Fill row by row.

18 min
160

State Machine DP

Model transitions between states. Stock problems are the canonical example.

18 min
161

Recursion & Memoization

Top-down DP. Cache the result of each subproblem. Never recompute.

16 min
162

Grid BFS/DFS Patterns

Mark visited. BFS for shortest. DFS for components. Multi-source for distances from all.

18 min
163

Fenwick Tree (BIT)

Range sum and point update in O(log n). Simpler than segment tree for prefix queries.

14 min
164

Heavy-Light Decomposition

Decompose tree into O(log n) chains. Enables range queries on any tree path.

18 min
165

Euler Tour (DFS Order)

Flatten a tree into an array. Subtree queries become range queries.

14 min
166

Mo's Algorithm

Sort offline queries to minimize total movement. O((n+q)√n) for range queries.

15 min
167

XOR Basis (Linear Basis)

Gaussian elimination on XOR. Find max XOR, k-th XOR value, XOR spanning set.

13 min
168

Euler Path & Circuit

Visit every EDGE exactly once. Hierholzer's algorithm. Degree condition check.

13 min
169

Divide & Conquer DP Optimization

Reduce O(n²k) DP to O(nk log n) when optimal split point is monotone.

16 min
170

Sqrt Decomposition

Divide array into √n blocks. O(√n) per query/update. No preprocessing needed.

14 min
171

Persistent Segment Tree

Keep all historical versions. Query any past state in O(log n). Share nodes across versions.

16 min
172

Treap & Ordered Set

BST + heap priorities. Split and merge in O(log n). Dynamic order statistics.

15 min
173

CDQ Divide and Conquer

Solve 3D partial order problems offline. Process left half, measure cross contributions.

16 min
174

Bitset & Bit-Parallel Algorithms

Process 64 elements at once with uint64 bitmasks. DP optimized by 64x.

13 min
175

Slope Trick

Maintain the piecewise-linear convex function via two heaps. DP in O(n log n).

15 min
176

Segment Tree Beats (Ji Driver)

Range chmin/chmax in O(n log²n). Tags break only when strictly better value exists.

17 min
177

Balanced Partition DP

Split array into groups with balanced sums. Fairness DP, multiway partition.

14 min
178

Profile DP (Broken Profile)

Count tilings column by column. State = which cells in current column are filled.

15 min
179

Aliens Trick (WQS Binary Search)

DP with "exactly k" constraint → binary search on cost penalty λ.

16 min
180

Arithmetic Progression DP

Count/find longest AP subsequences. State = (last, diff). Key: hash by difference.

14 min
181

Subsequence Counting

Count subsequences with constraints. DP on choices: include or exclude each element.

14 min
182

Sliding Window — Advanced Patterns

At-most-k trick: exactly-k = at-most-k minus at-most-(k-1). Frequency-based windows.

14 min
183

2D Prefix Sums & Difference Arrays

O(1) rectangle sum queries. 2D range updates with difference arrays.

12 min
184

DP Optimized with Deque

Sliding window DP: O(n²) → O(n). Deque maintains useful transitions.

13 min
185

Stock Trading DP

Buy/sell with cooldown, fees, k transactions. State machine DP on market states.

14 min
186

DP Space Optimization

Rolling array: reduce O(n²) DP space to O(n) or O(1). Fill order matters.

12 min
187

String Window Patterns

Minimum window substring, anagram in string, longest with K distinct chars.

13 min
188

Wildcard & Regex Matching

DP for pattern matching. Wildcard '?' and '*', regex '.' and '*'.

14 min
189

Counting Subarrays & Substrings

Count subarrays satisfying constraints. Prefix sums, two pointers, "at most K" trick.

13 min
190

Palindrome DP Problems

Minimum cuts, minimum insertions, count palindromic substrings. Interval DP.

14 min
191

Trapping Rain Water

Water trapped between heights. Two pointers, stack, 2D BFS variants.

13 min
192

Matrix Chain & Generalized Interval DP

Optimal parenthesization, burst balloons, stone merging. O(n³) interval DP.

14 min
193

Stone Game & Minimax DP

Both players play optimally. DP for competitive game results and optimal values.

13 min
194

HashMap + Prefix Sum Patterns

Count subarrays with target sum, equal 0s and 1s, balanced strings.

12 min

More chapters coming

Segment Trees, Network Flow, Number Theory deep dives - next up.