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 chaptersTwo Pointers
Prune half the search space at every step.
Sliding Window
Turn O(n²) subarray loops into O(n) with a moving window.
Binary Search
Eliminate half the search space every step.
Prefix Sum & Difference Array
Precompute prefix sums. Any range query becomes O(1).
Two Sum Family
One element + its complement. HashMap stores what you've seen. O(n) beats O(n²).
Array Manipulation Tricks
Rotate with 3 reverses. Mark visited in-place. Rearrange with index encoding.
Difference Array & Range Updates
Add delta to range [l,r] in O(1). Prefix sum to recover. Sweep line in 1D.
Contribution Technique
Count how many times each element contributes to the answer. Reverse the summation.
Binary Search on Answer
When you can check "is X achievable?" in O(f(n)), find optimal X in O(f(n) log range).
Permutation Patterns
Next permutation, cycle decomposition, inversions, k-th permutation in O(n).
Word Break & String Segmentation
Can we split a string into valid words? DP with trie or set lookup.
Shortest Supersequence & LCS Duality
SCS(s,t) = |s| + |t| - LCS(s,t). Find minimum string containing both as subsequences.
Kadane's Algorithm & Subarray Variants
Max subarray sum in O(n). Circular variant, k disjoint subarrays, submatrix.
Two Pointer — Advanced Patterns
3Sum, 4Sum, remove duplicates, partition. Multiple pointer coordination.
Cyclic Sort & Missing Numbers
Place each number at its correct index. Find missing/duplicate in O(n) O(1).
Array Rotation & Circular Problems
Rotate by k, search in rotated array, circular queue/buffer problems.
Next Permutation & Lexicographic Order
Find next/previous permutation in-place. Kth permutation, all permutations in order.
Part II - Linked Structures
20 chaptersLinked List
Dummy node. Slow/fast pointers. Reverse in-place.
Advanced Tree Structures
Segment tree for range queries. Fenwick for prefix sums. O(log n) both.
Sparse Table & Binary Lifting
Precompute powers of 2. Answer range min/max in O(1).
Segment Tree: Lazy Propagation
Range update in O(log n). Defer the work until you actually need it.
Cycle Detection
Floyd's tortoise and hare. O(n) time, O(1) space. Detects AND finds the cycle.
Tree Construction from Traversals
Preorder[0] = root. Inorder splits left/right. Find the split, recurse.
Lowest Common Ancestor (LCA)
Find common ancestor of two nodes. Binary lifting O(n log n). Euler tour + RMQ O(n).
DSU on Tree (Small-to-Large)
Heavy child inherits parent's data. Light children merged small-to-large. O(n log n).
Tree Diameter & Path Queries
Diameter via two BFS. Rerooting DP for all-root path queries. Longest path in O(n).
Offline LCA (Tarjan's)
Answer all LCA queries in O(n + q) using Union-Find. Process queries offline.
Tree Isomorphism & Canonical Forms
Two trees are isomorphic iff they have the same canonical form. AHU in O(n log n).
Persistent Union-Find (DSU with Rollback)
Undo union operations. Offline dynamic connectivity with O(n log²n).
Binary Lifting
Jump 2^k ancestors in O(log n). LCA, kth ancestor, path queries on trees.
Segment Tree Basics
Point updates and range queries in O(log n). Build, query, update.
Tree Path Problems
Root-to-leaf paths, path sums, max path through any nodes.
Iterative Tree & Graph Traversal
DFS without recursion. Explicit stack for inorder, preorder, postorder, Morris.
BST Operations & Properties
BST insert, delete, validate, floor/ceiling, kth element, convert to/from sorted.
Linked List Reversal Patterns
Reverse full list, reverse k-groups, reverse between positions, copy with random.
Tree Level-Order Variants
BFS tree traversals: zigzag, right side view, level averages, cousins.
Tree DP on General Trees
DP on trees with arbitrary number of children. Subtree properties, rerooting.
Part III - Hashing & Auxiliary Structures
14 chaptersHeap & Priority Queue
O(log n) access to the min or max. Always.
Trie (Prefix Tree)
Fast prefix lookup. One character per level.
Monotonic Stack & Queue
Next greater element in O(n). Sliding window max in O(n).
HashMap & Counting Patterns
Trading time for space. One pass with a map beats two nested loops.
Stack & Queue Patterns
LIFO for matching/nesting. FIFO for BFS/order. Deque for sliding extremes.
Counting Patterns
Count pairs, subarrays, paths. Always ask: what structure enables efficient counting?
K-th Element Patterns
QuickSelect for O(n), heap for O(n log k), binary search for implicit structures.
Monotonic Queue
Sliding window max/min in O(1). Deque keeps candidates in sorted order.
Two Heaps Pattern
Balance a max-heap and min-heap to maintain median in O(log n).
Bracket Sequences
Stack for matching. Count valid sequences. DP for generation. Min removals.
Amortized O(1) Patterns
O(1) average via "charge" analysis. Two stacks, stack with min, queue from stacks.
Expression Parsing & Evaluation
Stack-based evaluation. Shunting-Yard for precedence. Recursive descent parser.
Bitwise Trie (XOR Trie)
Binary trie on bit representation. Find max XOR pair in O(n log MAX).
K-Way Merge
Merge k sorted structures with a min-heap. Find smallest range, kth smallest.
Part IV - Core Algorithms
41 chaptersDynamic Programming
Overlapping subproblems + optimal substructure = DP.
Backtracking
Try every option. Undo. Move on.
Greedy Algorithms
Make the locally optimal choice. Hope it's globally optimal.
Shortest Path Algorithms
Dijkstra for non-negative weights. Bellman-Ford for negatives. Floyd for all pairs.
Bitmask DP
Subsets as integers. 2^n states where n ≤ 20.
Divide and Conquer
Split. Solve each half. Merge. Repeat until trivial.
Knapsack DP
Iterate backwards for 0/1. Forwards for unbounded. Know the difference.
Advanced Graph: SCC, Bridges & 2-SAT
Tarjan finds everything: SCCs, bridges, articulation points — one DFS.
Bipartite Graphs & Matching
2-colorable = bipartite. BFS/DFS detects it. Matching pairs them up optimally.
Coordinate Compression
Map large values to small ranks. Enables Fenwick/SegTree on value-based problems.
Topological Sort
Order nodes so all edges point forward. BFS (Kahn's) or DFS post-order.
Minimum Spanning Tree
Connect all nodes with minimum total edge weight. Kruskal or Prim.
Network Flow
Max flow = min cut. Dinic's runs in O(V²E). Models matching, assignment, feasibility.
Meet in the Middle
Split problem in half. Enumerate each half independently. Combine in O(n log n).
Convex Hull Trick
Optimize DP with min/max of linear functions. Maintains a convex hull of lines.
Centroid Decomposition
Divide tree at centroid. Every path passes through O(log n) centroids.
Line Sweep
Sweep a line across events. Sort by x, process events with a sorted structure.
2-SAT
Solve boolean formulas with 2-literal clauses in O(V+E) via SCC.
Bridges & Articulation Points
Find critical edges and vertices. DFS with low[] array. O(V+E).
Min-Cost Max-Flow
Find max flow with minimum total cost. SPFA/Bellman-Ford on residual graph.
Circulation & Flow with Lower Bounds
Edge has both minimum and maximum flow. Reduce to standard max-flow via supply/demand.
Bidirectional BFS
BFS from both source and target. Meet in the middle. Reduces O(b^d) to O(b^(d/2)).
A* Search
Dijkstra guided by a heuristic. Finds optimal path faster when heuristic is good.
Difference Constraints
x_j - x_i ≤ w → edge i→j with weight w. SSSP gives feasible solution.
Functional Graphs
Every node has exactly one outgoing edge. Each component = rho (ρ) shape: tail + cycle.
Matching via Maximum Flow
Bipartite matching = max flow in O(E√V). General matching = Blossom algorithm.
Graph Coloring
Assign colors so no adjacent vertices share a color. Greedy gives ≤ Δ+1 colors.
Top-K & Streaming Algorithms
Maintain top-K elements in streams. Heap-based selection, frequency tracking.
Strongly Connected Components
Tarjan's and Kosaraju's algorithms. Condense cycles into DAG of SCCs.
Graph State Space Search
BFS/Dijkstra on augmented states. (node, extra_state) as graph vertices.
Greedy Interval Problems
Activity selection, meeting rooms, interval scheduling. Sort + greedy sweep.
Constructive Algorithms
Build a valid answer from constraints. Greedy construction, invariant maintenance.
Backtracking with Pruning
Prune search space early. Bound functions, symmetry breaking, feasibility checks.
Multi-Source BFS & 0-1 BFS
BFS from multiple sources simultaneously. 0-1 BFS with deque for mixed weights.
Grid Island Problems
Connected components in grids. BFS/DFS flood fill, area, perimeter, enclosure.
Bellman-Ford & Negative Cycles
Shortest paths with negative edges. Detect negative cycles. SPFA optimization.
Jump Game Variants
Reachability and minimum jumps. BFS, greedy, DP on jump range problems.
Union-Find Applications
Connect components dynamically. Detect cycles, count components, earliest connection.
Greedy String Problems
Remove k digits, largest number, reorganize string. Monotone stack for ordering.
Graph Coloring & Bipartite Checking
Two-color graphs to find odd cycles. Divide into two groups satisfying constraints.
Floyd-Warshall All-Pairs Shortest Paths
O(V³) all-pairs shortest paths. Transitive closure, detect negative cycles.
Part V - Strings, Sequences & Grid
18 chaptersString Algorithms
KMP, Z-algo, rolling hash — pattern matching in O(n).
String Matching Algorithms
KMP: O(n+m) search using failure function. Rabin-Karp: hash-based. Z-algorithm: substring in O(n).
Sequences — LIS, LCS & More
LIS in O(n log n). LCS from DP. Every sequence has a structure.
Matrix & Shape Problems
Spiral traversal, rotation, 2D prefix sums — grids have patterns.
String DP
dp[i][j] = answer for s1[0..i-1] and s2[0..j-1]. Match or skip.
Palindrome Patterns
Expand from center, or DP on intervals. Two approaches cover every palindrome problem.
String Hashing & Rolling Hash
Compare substrings in O(1) after O(n) preprocessing. Rabin-Karp for pattern matching.
Suffix Array & LCP Array
Sort all suffixes. Build LCP array. Enables O(n log n) solutions for hard string problems.
Aho-Corasick Automaton
Multi-pattern string matching in O(n + m + k). KMP generalized to many patterns.
Z-Function & String Matching
z[i] = length of longest string starting at i that matches a prefix. O(n) pattern matching.
Manacher's Algorithm
Find all palindromic substrings in O(n). Extends each palindrome using previous results.
Suffix Automaton (SAM)
Compact structure for all substrings. O(n) build. All substring queries in O(n).
Palindrome Automaton (Eertree)
Build all distinct palindromic substrings in O(n). Count occurrences in O(n).
String Rotations & Booth's Algorithm
Lexicographically minimum rotation in O(n). Check rotation in O(n) via concatenation.
Lyndon Factorization
Every string = unique product of decreasing Lyndon words. Duval's algorithm O(n).
String Construction & Transformation
Build target strings via DP. Edit distance, word ladder, minimum operations.
String Decode & Transform Patterns
Decode encoded strings, run-length encoding, parenthesis-based nesting.
String Parsing & Integer Conversion
atoi, add binary/strings, multiply strings, number to/from base.
Part VI - Math & Discrete
27 chaptersMath & Number Theory
GCD, primes, modular arithmetic — the engine behind CP.
Bit Manipulation
XOR is your best friend. Masks are your toolkit.
Combinatorics & Counting
nCr, inclusion-exclusion, Catalan numbers — count without listing.
Game Theory — Nim & Sprague-Grundy
XOR determines the winner. Grundy values generalize everything.
Computational Geometry
Cross products determine orientation. Convex hull wraps everything.
Number Theory
GCD, primes, modular arithmetic — the math behind the tricks.
Probability & Expected Value DP
E[X] = Σ p(outcome) × value(outcome). DP builds it up iteratively.
Ternary Search
Find minimum of unimodal function in O(log n). Divide range into thirds.
FFT & Polynomial Multiplication
Multiply polynomials in O(n log n). Convolution. Count pairs summing to k.
Sprague-Grundy Theorem
Every impartial game = Nim pile. Grundy value = mex of reachable states.
Chinese Remainder Theorem
Solve x ≡ a1 (mod m1), x ≡ a2 (mod m2), ... in one shot. Extended Euclidean key.
Convex Hull
Smallest convex polygon enclosing all points. Graham scan O(n log n). Andrew's monotone chain.
Inclusion-Exclusion Principle
|A∪B| = |A| + |B| - |A∩B|. Generalize to n sets. Count with constraints.
Catalan Numbers
C(n) counts balanced parentheses, BST shapes, polygon triangulations, and more.
Josephus Problem & Circular Elimination
n people in a circle, every k-th eliminated. Find survivor's position in O(n).
Sieve Variants & Multiplicative Functions
Linear sieve, Euler's totient sieve, Möbius function. Each number factored once.
Burnside's Lemma
Count distinct objects under symmetry. Average fixed points over group actions.
Gray Code & Bit Tricks
Adjacent Gray codes differ by one bit. Bit tricks: lowbit, popcount, bit pairs.
Gaussian Elimination over GF(2)
Solve XOR linear systems. Find XOR basis rank. Determine reachability by XOR.
Lucas Theorem & Combinatorics Mod p
C(n,k) mod prime p in O(log_p n). Pascal mod p has fractal structure.
Lattice Paths & Ballot Problems
Count paths on a grid with constraints. Reflection principle. Catalan structures.
Advanced Counting DP
Partition numbers, Bell numbers, Stirling numbers. DP on combinatorial structures.
Rotating Calipers & Convex Polygon Queries
Farthest pair, diameter, closest parallel edges in O(n) after O(n log n) hull.
Carry & Digit Manipulation DP
DP tracking carries in arithmetic operations. Count valid assignments with constraints.
Random Walk & Expected Value
Expected number of steps in random processes. Linear system or DP on states.
Number Manipulation Tricks
Reverse digits, Roman numerals, palindrome numbers, Excel column mapping.
Bit Counting & Manipulation Tricks
Count set bits, Hamming distance, Brian Kernighan's trick, DP counting bits.
Part VII - Advanced Topics
13 chaptersLinear Algebra & Matrix Exponentiation
Speed up any linear recurrence from O(n) to O(log n) with matrix power.
Numerical Methods & Optimization
Binary search on reals. Ternary search on unimodal functions. Simulated annealing for hard optimizations.
Scheduling & Interval Problems
Sort by deadline. Greedy + heap beats brute force every time.
Shapes & 2D Geometry
Triangles, rectangles, circles — every shape reduces to distance + area math.
Miscellaneous Algorithms
BFS on state space, majority vote, puzzle inversions — the patterns that don't fit elsewhere.
Design Data Structures
LRU, LFU, iterators — combine primitives for O(1) every operation.
Sorting Algorithms & Applications
Non-comparison sorts beat O(n log n). Sorting enables patterns: binary search, two pointers.
Simulation & Implementation
Do exactly what the problem says. Edge cases are the challenge.
Matrix Exponentiation
Compute linear recurrences in O(k³ log n). Fibonacci in O(log n).
Randomized Algorithms
Random choices eliminate worst cases. Reservoir sampling, random pivot, shuffle.
Multiset & Ordered Set Patterns
Maintain sorted collections dynamically. Order statistics, rank queries, range operations.
LRU & LFU Cache Design
O(1) get/put with HashMap + doubly linked list. LFU with frequency buckets.
Matrix Operations & Transformations
Rotate 90°, transpose, spiral traversal, search in sorted matrix.
Part VIII - Cross-Topic Deep Dives
42 chaptersBFS vs DFS — When to Use Each
Shortest path → BFS. Connected components → DFS. Know which in 10 seconds.
Interval Problems — The Complete Guide
Sort by start. Merge overlaps. Sweep with a heap. All interval problems reduce to three patterns.
DP on Trees
Postorder + return value = tree DP. Same template solves diameter, max path, subtree counts.
Union-Find (Disjoint Set Union)
Find the root. Union the sets. Near-constant time with path compression.
Digit DP
Count integers in [0, N] satisfying a digit property.
Interval DP
dp[i][j] = best answer for subproblem on range [i..j].
Grid DP
dp[i][j] depends on neighbors. Fill row by row.
State Machine DP
Model transitions between states. Stock problems are the canonical example.
Recursion & Memoization
Top-down DP. Cache the result of each subproblem. Never recompute.
Grid BFS/DFS Patterns
Mark visited. BFS for shortest. DFS for components. Multi-source for distances from all.
Fenwick Tree (BIT)
Range sum and point update in O(log n). Simpler than segment tree for prefix queries.
Heavy-Light Decomposition
Decompose tree into O(log n) chains. Enables range queries on any tree path.
Euler Tour (DFS Order)
Flatten a tree into an array. Subtree queries become range queries.
Mo's Algorithm
Sort offline queries to minimize total movement. O((n+q)√n) for range queries.
XOR Basis (Linear Basis)
Gaussian elimination on XOR. Find max XOR, k-th XOR value, XOR spanning set.
Euler Path & Circuit
Visit every EDGE exactly once. Hierholzer's algorithm. Degree condition check.
Divide & Conquer DP Optimization
Reduce O(n²k) DP to O(nk log n) when optimal split point is monotone.
Sqrt Decomposition
Divide array into √n blocks. O(√n) per query/update. No preprocessing needed.
Persistent Segment Tree
Keep all historical versions. Query any past state in O(log n). Share nodes across versions.
Treap & Ordered Set
BST + heap priorities. Split and merge in O(log n). Dynamic order statistics.
CDQ Divide and Conquer
Solve 3D partial order problems offline. Process left half, measure cross contributions.
Bitset & Bit-Parallel Algorithms
Process 64 elements at once with uint64 bitmasks. DP optimized by 64x.
Slope Trick
Maintain the piecewise-linear convex function via two heaps. DP in O(n log n).
Segment Tree Beats (Ji Driver)
Range chmin/chmax in O(n log²n). Tags break only when strictly better value exists.
Balanced Partition DP
Split array into groups with balanced sums. Fairness DP, multiway partition.
Profile DP (Broken Profile)
Count tilings column by column. State = which cells in current column are filled.
Aliens Trick (WQS Binary Search)
DP with "exactly k" constraint → binary search on cost penalty λ.
Arithmetic Progression DP
Count/find longest AP subsequences. State = (last, diff). Key: hash by difference.
Subsequence Counting
Count subsequences with constraints. DP on choices: include or exclude each element.
Sliding Window — Advanced Patterns
At-most-k trick: exactly-k = at-most-k minus at-most-(k-1). Frequency-based windows.
2D Prefix Sums & Difference Arrays
O(1) rectangle sum queries. 2D range updates with difference arrays.
DP Optimized with Deque
Sliding window DP: O(n²) → O(n). Deque maintains useful transitions.
Stock Trading DP
Buy/sell with cooldown, fees, k transactions. State machine DP on market states.
DP Space Optimization
Rolling array: reduce O(n²) DP space to O(n) or O(1). Fill order matters.
String Window Patterns
Minimum window substring, anagram in string, longest with K distinct chars.
Wildcard & Regex Matching
DP for pattern matching. Wildcard '?' and '*', regex '.' and '*'.
Counting Subarrays & Substrings
Count subarrays satisfying constraints. Prefix sums, two pointers, "at most K" trick.
Palindrome DP Problems
Minimum cuts, minimum insertions, count palindromic substrings. Interval DP.
Trapping Rain Water
Water trapped between heights. Two pointers, stack, 2D BFS variants.
Matrix Chain & Generalized Interval DP
Optimal parenthesization, burst balloons, stone merging. O(n³) interval DP.
Stone Game & Minimax DP
Both players play optimally. DP for competitive game results and optimal values.
HashMap + Prefix Sum Patterns
Count subarrays with target sum, equal 0s and 1s, balanced strings.
More chapters coming
Segment Trees, Network Flow, Number Theory deep dives - next up.