Home
Welcome to My Learning Journal
Hey, Iβm Akib π β a Full Stack Developer & DevOps Engineer.
This is my personal collection of notes, guides, and cheat sheets on various topics in technology.
I use it both as a quick reference and as a way to share knowledge with others.
ΛΛΛβΛΛΛ β Connect with me:
π What You'll Find Here
This site is automatically built and deployed from my
NixOS configuration repository using Nix and mdBook.
- π§ Linux β Installation guides, system tools, and server configs.
- πΎ Databases β Notes on MySQL, Postgres, and more.
- π Deployment β Step-by-step guides on deploying applications.
- π οΈ Dev Tools β Shell scripts, Git, automation tricks, and configs.
β¨ Happy learning!
Itβs Mon Nov 30 16:21:47 UTC 2026 β a great day to document something new.
The Algorithms Handbook
Roadmap, Complexity Primer, Comparison Tables, Decision Guide & Cheat Sheets
How This Guide Is Organized
Like the companion Data Structures guide, this is a multi-file textbook β each algorithm (or tight cluster of related algorithms) gets its own chapter, following a consistent 15-section template (Introduction β Intuition β Step-by-Step Working β Complexity β Advantages/Limitations β Real-World Applications β C++ Implementation β Code Walkthrough β Dry Run β Complexity Table β Common Mistakes β Interview Questions β Practice Problems β Summary). This file is the spine: the roadmap, the complexity-analysis primer every later chapter assumes, the pattern-recognition decision tree, comparison tables, and cheat sheets.
Status: complete. All 19 chapters (00-18) are delivered, covering every category from the original roadmap below, including the βAdvanced Algorithmsβ leaf.
Full table of contents:
00_roadmap_and_strategy.mdβ you are here01_binary_search.md02_simple_sorts.md(Bubble, Selection, Insertion)03_merge_sort.md04_quick_sort.md05_heap_sort.md06_non_comparison_sorts.md(Counting, Radix, Bucket)07_two_pointer.md08_sliding_window.md09_prefix_sum.md10_greedy_algorithms.md11_backtracking.md12_dynamic_programming_fundamentals.md13_dynamic_programming_classic_problems.md(LCS, LIS, Coin Change)14_graph_algorithms.md(Floyd-Warshall, cycle detection)15_tree_algorithms.md(Traversals, LCA, Diameter)16_string_algorithms.md(pattern recognition capstone, Rolling Hash)17_advanced_dp.md(Bitmask DP, DP on Trees)18_advanced_techniques.md(Meet in the Middle, Heavy-Light Decomposition) β final chapter
Part 1 β The Learning Roadmap
Prerequisites
β
βββ Programming Fundamentals
βββ Mathematics Basics (logs, combinatorics, modular arithmetic)
βββ Recursion (call stack, base/recursive case)
βββ Big-O Analysis (this file's Part 0, below)
β
βββ Searching
β βββ Linear Search β baseline, no assumptions about data
β βββ Binary Search β requires sorted data, halves search space
β
βββ Sorting
β βββ Bubble / Selection / Insertion β simple, O(nΒ²), good for teaching invariants
β βββ Merge Sort β divide & conquer, stable, O(n log n) guaranteed
β βββ Quick Sort β divide & conquer, in-place, O(n log n) average
β βββ Heap Sort β uses the Heap (Data Structures guide, Ch.5)
β βββ Counting / Radix / Bucket β non-comparison sorts, O(n+k) under constraints
β
βββ Recursion & Divide-and-Conquer β foundation for Merge/Quick Sort, many tree/graph algos
β
βββ Array/String Techniques
β βββ Two Pointer β opposite/same direction, fast-slow
β βββ Sliding Window β fixed/variable window
β βββ Prefix Sum β 1D/2D range-sum precomputation
β
βββ Greedy Algorithms β needs proof-of-correctness thinking (exchange argument, cut property)
β
βββ Backtracking β needs recursion + state-space thinking
β
βββ Dynamic Programming β needs recursion + overlapping-subproblem recognition
β
βββ Graph Algorithms β needs Stack/Queue/Heap/DSU (Data Structures guide)
β
βββ Tree Algorithms β needs Binary Tree/BST (Data Structures guide)
β
βββ String Algorithms β needs arrays + hashing (KMP/Z/Rabin-Karp already
β covered in the Data Structures guide, Ch.2 β
β this guide's String chapter cross-references it)
β
βββ Advanced Algorithms β Bitmask DP, DP on trees, meet-in-the-middle,
heavy-light decomposition (overview-level)
Why this order?
| Stage | Why it comes here | Prerequisites | Learning Outcome |
|---|---|---|---|
| Big-O primer | Every later chapterβs βwhy this complexityβ section assumes fluency here | Basic programming | Ability to derive, not just quote, an algorithmβs complexity |
| Searching | Simplest possible algorithms; binary search is the first real βwhy does halving workβ insight | Big-O | Recognize when sorted structure enables faster search |
| Sorting | Comparison-based sorts teach recursion (merge/quick), invariants (bubble/insertion), and heap reuse (heap sort) | Big-O, arrays | Understand the O(n log n) comparison-sort lower bound and how non-comparison sorts escape it |
| Recursion/D&C | Merge sort and quick sort are the cleanest possible teaching examples of divide-and-conquer | Recursion basics | Recognize the βdivide, solve, combineβ pattern everywhere |
| Two Pointer / Sliding Window / Prefix Sum | Lightweight array techniques that solve a huge fraction of βeasy/mediumβ interview problems | Arrays, recursion | Instant pattern recognition for a whole problem class |
| Greedy | Needs the discipline of proving local choices lead to a global optimum | Sorting, basic proof intuition | Recognize when greedy is provably correct vs. when itβs just a heuristic |
| Backtracking | Systematic exhaustive search β a generalization of recursion with pruning | Recursion | Build state-space search with correct pruning |
| Dynamic Programming | Requires recognizing overlapping subproblems β the single hardest pattern-recognition skill in this guide | Recursion, backtracking | Convert exponential recursion into polynomial time via memoization/tabulation |
| Graph Algorithms | Needs Stack/Queue/Heap/DSU already built in the Data Structures guide | Data Structures Ch.3,4,5,17 | Model and solve connectivity, shortest-path, and ordering problems |
| Tree Algorithms | Needs BST/Binary Tree fluency | Data Structures Ch.7 | Solve hierarchical structure problems (LCA, diameter, traversal-based DP) |
| String Algorithms | Builds directly on Data Structures Ch.2 (KMP/Z/Rabin-Karp) | Data Structures Ch.2 | Recognize and apply pattern-matching techniques beyond simple search |
| Advanced | Combines everything above in novel ways | All prior stages | Handle competitive-programming-level and system-scale problems |
Suggested Timeline (self-paced, ~14-16 weeks at 1-2 hrs/day)
| Week | Focus | Mini Project |
|---|---|---|
| 1 | Big-O primer, Linear/Binary Search | Implement binary search + all its variants (lower/upper bound, search on answer) |
| 2 | Bubble, Selection, Insertion Sort | Visualize each sortβs swap count on the same input |
| 3 | Merge Sort, Quick Sort | Benchmark both on random vs. adversarial (sorted, reverse-sorted) input |
| 4 | Heap Sort, Counting/Radix/Bucket Sort | Sort 1M integers with each algorithm, compare wall-clock time |
| 5 | Two Pointer, Sliding Window | Solve 10 problems using each pattern |
| 6 | Prefix Sum (1D and 2D) | Build a range-query answering tool for a matrix |
| 7 | Greedy Algorithms | Implement Huffman Coding end-to-end (encode + decode a real file) |
| 8 | Backtracking | N-Queens and Sudoku solvers with pruning visualization |
| 9-10 | Dynamic Programming (1D, 2D, knapsack-family) | Solve the βDP 100β style progressive problem set |
| 11 | Graph Algorithms β traversal & shortest path | Build a mini route-planner using Dijkstra |
| 12 | Graph Algorithms β MST, topological sort, DSU | Implement Kruskalβs + a build-system dependency resolver |
| 13 | Tree Algorithms | LCA + tree diameter on a randomly generated tree |
| 14 | String Algorithms | Implement KMP/Z/Rabin-Karp from scratch, benchmark against std::string::find |
| 15-16 | Advanced topics + full mock interviews | Timed mixed problem sets across all patterns |
Part 0 β Complexity Analysis Primer
(Every later chapterβs βwhy does this complexity occurβ explanation assumes this section.)
Big-O (Ξ) describes an upper bound on growth rate β βthis algorithmβs cost grows no faster than this function, for large enough input.β Itβs the most commonly cited bound because it describes the worst case guarantee.
Big-Omega (Ξ©) describes a lower bound β βthis algorithmβs cost grows at least as fast as this function.β Used to prove a problemβs inherent difficulty (e.g., βany comparison-based sort is Ξ©(n log n)β).
Big-Theta (Ξ) describes a tight bound β both upper and lower simultaneously; βthis algorithmβs cost grows exactly at this rate.β When people casually say βO(n log n)β for merge sort, they usually mean the tighter Ξ(n log n), since merge sortβs best, average, and worst case are all the same order.
Growth rate intuition (small β large, for input size n):
O(1) < O(log n) < O(n) < O(n log n) < O(nΒ²) < O(nΒ³) < O(2βΏ) < O(n!)
Concretely, for n = 1,000,000:
O(log n) β 20
O(n) = 1,000,000
O(n log n) β 20,000,000
O(nΒ²) = 1,000,000,000,000 β already impractical
O(2βΏ) = astronomically larger than atoms in the universe
Time Complexity measures operations as a function of input size. Space Complexity measures extra memory used (beyond the input itself) as a function of input size β always ask βdoes this include the input, or just auxiliary space?β (convention varies; this guide always states which explicitly).
Amortized Analysis answers βwhatβs the average cost per operation across a whole sequence, even if individual operations vary wildly?β The canonical example (from the Data Structures guide): a dynamic arrayβs push_back is O(n) on the rare occasion it triggers a resize, but O(1) amortized across all pushes, because resizes become exponentially rarer as the array grows β the total cost of all resizes across n pushes sums to O(n), i.e., O(1) each on average.
Why βwhyβ matters more than βwhatβ: knowing merge sort is βO(n log n)β is memorization. Knowing itβs O(n log n) because the recursion splits the array into log n levels, and each level does O(n) total work merging β thatβs understanding, and itβs what lets you derive the complexity of an algorithm youβve never seen before, which is exactly what interviews and novel real-world problems demand.
Part 4 β Algorithm Pattern Recognition (Decision Tree)
START: What does the problem look like?
β
βββ Is the input already sorted, or can you sort it cheaply, and you need to find something?
β βββ Exact value β Binary Search β O(log n)
β βββ Boundary/count ("first index β₯ X", "count of elements β€ X") β Lower/Upper Bound Binary Search
β βββ The "found value" itself is monotonic in some parameter you control β Binary Search on the Answer
β
βββ Do you need to reorder the data itself?
β βββ Need stability + guaranteed O(n log n) + don't mind extra memory β Merge Sort
β βββ Need in-place + good average case, memory-constrained β Quick Sort
β βββ Already have (or can build) a heap, or need O(n log n) worst-case + in-place β Heap Sort
β βββ Keys are small integers / bounded range β Counting Sort / Radix Sort / Bucket Sort (O(n+k))
β
βββ Does the problem involve a contiguous subarray/substring with a running condition?
β βββ Fixed-size window ("max sum of any k consecutive elements") β Sliding Window (fixed)
β βββ Variable-size window ("smallest window containing X") β Sliding Window (variable)
β βββ Need repeated range-sum queries over a static array β Prefix Sum
β
βββ Does the problem involve pairs/triples in a sorted array, or a cycle/midpoint in a sequence?
β βββ "Find pair summing to target" in sorted array β Two Pointer (opposite direction)
β βββ "Remove duplicates in-place", "partition" β Two Pointer (same direction)
β βββ "Detect a cycle", "find the middle" β Fast & Slow Pointer
β
βββ Are you making a sequence of choices, and does picking the LOCALLY best option provably lead to
β the GLOBALLY best outcome (provable via exchange argument or matroid/cut-property structure)?
β βββ Yes, and you can prove it β Greedy
β βββ Not provable, but choices interact / overlap β likely Dynamic Programming instead
β
βββ Do you need to explore ALL valid configurations (or find one that satisfies constraints),
β with the ability to abandon a branch early once it's clearly invalid?
β βββ Backtracking (N-Queens, Sudoku, generating permutations/subsets/combinations)
β
βββ Does the problem ask for an optimal value (min/max/count) over choices, AND do smaller
β subproblems repeat/overlap when you try to solve it recursively?
β βββ Yes β Dynamic Programming (memoization if recursion is natural, tabulation for full control)
β βββ No overlap β plain recursion or divide-and-conquer is enough, no DP needed
β
βββ Does the problem involve a network of connections (vertices/edges)?
β βββ Need to visit everything / find connectivity β BFS or DFS
β βββ Need shortest path, non-negative weights β Dijkstra
β βββ Need shortest path, negative weights possible β Bellman-Ford
β βββ Need shortest path between ALL pairs β Floyd-Warshall
β βββ Need cheapest way to connect everything β MST (Kruskal's or Prim's)
β βββ Need a valid processing order given "must precede" constraints β Topological Sort
β βββ Need to repeatedly answer "are these connected?" as edges are added β Union-Find (DSU)
β
βββ Does the problem involve a hierarchical (tree) structure specifically?
β βββ Need to visit nodes in a specific order β Tree Traversal (pre/in/post/level-order)
β βββ Need the common ancestor of two nodes β Lowest Common Ancestor
β βββ Need the longest path between any two nodes β Tree Diameter
β
βββ Does the problem involve matching/searching within text?
βββ Single pattern, need airtight worst-case guarantee β KMP or Z-Function
βββ Multiple patterns, or approximate/hash-based matching acceptable β Rabin-Karp / Rolling Hash
βββ Many prefix queries against a fixed dictionary β Trie (see Data Structures guide, Ch.9)
Reasoning behind key decisions:
- Binary Search requires monotonicity, not just sorted data β the real requirement is βcan I define a yes/no predicate thatβs false-then-true (or true-then-false) across the search space?β Sorted arrays are the most common such space, but βbinary search on the answerβ applies the same halving logic to any monotonic predicate, even without an explicit array (e.g., βcan I complete all tasks within X hours?β).
- Greedy vs. DP is the single most-tested distinction in interviews: greedy commits to a choice and never revisits it, which only works when you can prove no future information could ever make an earlier greedy choice regrettable. The moment a locally-best choice can be invalidated by later context, you need DPβs βtry all options, remember the bestβ approach instead.
- Backtracking vs. DP: both explore a state space, but backtracking is for enumeration/existence problems (find all/any valid configurations) with pruning, while DP is for optimization/counting problems with overlapping subproblems where memoizing repeated states turns exponential exploration into polynomial time.
Part 5 β Comparison Tables
Linear Search vs. Binary Search
| Aspect | Linear Search | Binary Search |
|---|---|---|
| Precondition | None | Data must be sorted (or monotonic predicate) |
| Time Complexity | O(n) | O(log n) |
| Space Complexity | O(1) | O(1) iterative, O(log n) recursive |
| Use case | Unsorted/small data, one-off search | Repeated searches on sorted/static data |
Merge Sort vs. Quick Sort
| Aspect | Merge Sort | Quick Sort |
|---|---|---|
| Worst-case time | O(n log n) β guaranteed | O(nΒ²) β rare with good pivot strategy, but possible |
| Average-case time | O(n log n) | O(n log n) |
| Space | O(n) extra (not in-place) | O(log n) extra (in-place, recursion stack) |
| Stability | Stable | Not stable (standard implementation) |
| Practical speed | Slightly slower (memory allocation, copying) | Usually faster in practice (better cache locality, in-place) |
| Use case | Need stability, guaranteed worst case, external/linked-list sorting | General-purpose, memory-constrained, average-case matters more than worst-case |
Greedy vs. Dynamic Programming
| Aspect | Greedy | Dynamic Programming |
|---|---|---|
| Decision process | Commit to locally optimal choice, never revisit | Explore/remember all relevant sub-decisions |
| Correctness requirement | Must PROVE local optimality β global optimality | Requires identifying overlapping subproblems + optimal substructure |
| Time complexity | Usually faster (O(n log n) or O(n)) | Usually slower (O(nΒ²), O(nΒ·k), etc. depending on state space) |
| Example | Activity Selection, Huffman Coding | Knapsack, LCS, LIS, Coin Change |
| When greedy fails | Coin Change with arbitrary denominations (not canonical system) β greedy can give a suboptimal answer | β |
Backtracking vs. Branch and Bound
| Aspect | Backtracking | Branch and Bound |
|---|---|---|
| Goal | Find any/all valid solutions satisfying constraints | Find the OPTIMAL solution among many valid ones |
| Pruning criterion | Constraint violation (this branch is invalid) | Bound comparison (this branch canβt beat the best found so far, even if valid) |
| Typical problems | N-Queens, Sudoku, permutations/subsets | Traveling Salesman, job scheduling with cost bounds |
| Complexity | Still exponential worst case, but pruning helps enormously in practice | Also exponential worst case, but bound-based pruning can eliminate huge portions of the search space |
Binary Search vs. Linear Search β see above (kept together intentionally for quick reference)
Primβs vs. Kruskalβs β see the Data Structures guide, Chapter 13, for the full comparison (MST algorithms are covered there since theyβre graph-structure-driven)
Dijkstraβs vs. Bellman-Fordβs β see the Data Structures guide, Chapter 14, for the full comparison
Memoization vs. Tabulation
| Aspect | Memoization (Top-Down) | Tabulation (Bottom-Up) |
|---|---|---|
| Direction | Start from the original problem, recurse down, cache results | Start from base cases, build up to the original problem |
| Implementation style | Recursive + a cache (map/array) | Iterative, filling a table (usually an array) |
| Stack usage | Uses the call stack β risk of stack overflow for deep recursion | No recursion β no stack overflow risk |
| Solves only needed subproblems? | Yes β only computes states actually reached | No β typically computes all states up to the target, even unneeded ones |
| Ease of writing | Often more intuitive β mirrors the natural recursive definition | Requires figuring out the correct iteration order upfront |
| Typical performance | Slightly slower (function call overhead) | Slightly faster (no call overhead, better cache behavior) |
Part 6 β Master Cheat Sheet
Complexity Recap Across Categories
| Category | Typical Best Case | Typical Worst Case | Typical Space |
|---|---|---|---|
| Linear Search | O(1) | O(n) | O(1) |
| Binary Search | O(1) | O(log n) | O(1) |
| Bubble/Selection/Insertion Sort | O(n) or O(nΒ²) (varies) | O(nΒ²) | O(1) |
| Merge Sort | O(n log n) | O(n log n) | O(n) |
| Quick Sort | O(n log n) | O(nΒ²) | O(log n) |
| Heap Sort | O(n log n) | O(n log n) | O(1) |
| Counting/Radix Sort | O(n+k) | O(n+k) | O(n+k) |
| Two Pointer / Sliding Window | O(n) | O(n) | O(1) |
| Prefix Sum (query after build) | O(1) query, O(n) build | O(1) query | O(n) |
| Backtracking (general) | Problem-dependent | O(bα΅) (branching factor b, depth k) | O(k) |
| Dynamic Programming | O(states Γ transition cost) | Same (DP has no βluckyβ best case typically) | O(states) or O(1D slice) with optimization |
| BFS / DFS | O(V+E) | O(V+E) | O(V) |
| Dijkstraβs | O(E log V) | O(E log V) | O(V) |
| Floyd-Warshall | O(VΒ³) | O(VΒ³) | O(VΒ²) |
Memory Tricks
- βBinary Search halves; Linear Search crawls.β
- βMerge Sort divides evenly and merges smartly (guaranteed, not in-place); Quick Sort divides unevenly around a pivot but usually wins the speed race (in-place, not guaranteed).β
- βGreedy: prove first, then trust. DP: donβt trust, try everything, remember what worked.β
- βBacktracking asks βis this valid?β Branch and Bound asks βcan this still win?ββ
- βIf subproblems overlap, memoize. If they donβt, plain recursion/divide-and-conquer is already optimal.β
Interview Readiness Checklist (fill in as you complete each chapter)
- Searching β binary search + all boundary variants implemented, 10+ problems solved
- Sorting β all 9 algorithms implemented, can explain stability/in-place trade-offs, 10+ problems
- Two Pointer / Sliding Window / Prefix Sum β instant pattern recognition, 15+ problems
- Greedy β can construct an exchange-argument proof for at least 2 classic problems
- Backtracking β N-Queens and Sudoku implemented with pruning, 10+ problems
- Dynamic Programming β comfortable converting recursion β memoization β tabulation β space-optimized, 20+ problems
- Graph Algorithms β all traversal/shortest-path/MST/topo-sort algorithms implemented, 15+ problems
- Tree Algorithms β LCA and diameter implemented, 10+ problems
- String Algorithms β KMP/Z/Rabin-Karp implemented, 10+ problems
- Advanced DP β Bitmask DP and DP on Trees implemented, 5+ problems
- Advanced Techniques β can describe Meet in the Middle and Heavy-Light Decomposition and when each applies
- Mixed mock interviews β can identify the correct pattern within 2 minutes of reading a new problem
The guide is complete. Start at 01_binary_search.md and work through in order, or jump straight to whichever chapter matches what youβre studying β every chapter cross-references the others it builds on (both within this guide and in the companion Data Structures guide), so you can also navigate by following those references. See 18_advanced_techniques.md for the closing reflection tying the whole guide together.
Chapter 1: Binary Search
Study time: ~4-6 hours | Prerequisite: Big-O primer (see roadmap file) | Difficulty: Beginner (basics) to Intermediate (search-on-answer variant)
1. Introduction
Definition: Binary Search finds a target value (or a boundary) within a sorted (or otherwise monotonic) search space by repeatedly halving the space β comparing the target against the middle element and discarding the half that canβt contain it.
Purpose: To reduce search time from O(n) (checking every element) to O(log n) β an exponential improvement that becomes dramatic at scale (searching a billion-element sorted array takes ~30 comparisons, not a billion).
Problem solved: βFind whether/where a target exists in a sorted collection,β and more generally, βfind the boundary point where a monotonic condition flips from false to true (or vice versa).β
2. Intuition
Imagine guessing a number between 1 and 100 that someone is thinking of, where after each guess they tell you βhigherβ or βlower.β The optimal strategy is never to guess sequentially (1, 2, 3, β¦) β itβs to always guess the middle of the remaining range. Guess 50: if βhigher,β youβve just eliminated 50 numbers in one move. Guess 75 next: eliminate 25 more. This halving is exactly binary search β and itβs the natural strategy any reasonable person derives on their own once they realize the βhigher/lowerβ feedback is available for every guess, not just the first one.
The key insight that makes this valid: the search space must be monotonic β once you know the target is βhigherβ than 50, you can trust that itβs also higher than every number below 50, without re-checking them. This trust is exactly what βsortedβ (or βmonotonic predicateβ) guarantees, and itβs the one precondition binary search can never work without.
3. Step-by-Step Working
Example: find 23 in [2, 5, 8, 12, 16, 23, 38, 45, 56, 72] (indices 0-9).
low=0, high=9
Step 1: mid = (0+9)/2 = 4 β arr[4]=16. 23 > 16 β search RIGHT half β low = 5
Step 2: low=5, high=9, mid=(5+9)/2=7 β arr[7]=45. 23 < 45 β search LEFT half β high = 6
Step 3: low=5, high=6, mid=(5+6)/2=5 β arr[5]=23. MATCH! Return index 5.
Visually, the search space shrinks: [10 elements] β [5 elements] β [2 elements] β found. Each step at least halves the remaining space β this is the entire source of the O(log n) bound.
Boundary variants (Lower Bound / Upper Bound):
- Lower Bound: the first index where
arr[i] >= target(first position you could insert target and keep the array sorted, if there are ties, inserting before them). - Upper Bound: the first index where
arr[i] > target(insertion point after any existing duplicates of target).
arr = [2, 5, 5, 5, 8, 12], target = 5:
Lower Bound β index 1 (first 5)
Upper Bound β index 4 (first element greater than 5, i.e., where 8 sits)
Binary Search on the Answer: the same halving logic applied to a value, not an array index, when a yes/no predicate about that value is monotonic. Example: βwhatβs the minimum boat capacity to ferry all people across within D trips?β β as capacity increases, βcan we do it in β€ D trips?β flips from false to true exactly once, and never flips back β so you binary search over capacity values, not array positions.
4. Complexity Analysis
Time: O(log n). Each comparison discards at least half the remaining search space. Starting from n elements, after k halvings you have n/2^k elements left; the search ends when this reaches 1, i.e., n/2^k = 1 β k = logβ(n). This is why the complexity is logarithmic β itβs the direct mathematical consequence of βalways eliminate half,β not an empirical observation.
Space: O(1) iterative, O(log n) recursive (the recursion depth equals the number of halvings, i.e., O(log n) stack frames if implemented recursively).
Why it canβt be faster than O(log n) for comparison-based search: each comparison yields at most 1 bit of information (βhigherβ or βlowerβ), and you need enough bits to distinguish among n possibilities β information-theoretically, that requires at least logβ(n) comparisons in the worst case. Binary search achieves this lower bound exactly, making it asymptotically optimal for comparison-based search on sorted data.
5. Advantages
- O(log n) β extraordinarily fast, scales gracefully even to enormous datasets.
- O(1) extra space (iterative version) β no auxiliary memory needed.
- Generalizes far beyond βfind X in an arrayβ β any monotonic yes/no predicate over a range can be searched this way (binary search on the answer).
6. Limitations
- Requires sorted (or monotonic) data β if the data isnβt sorted and canβt be cheaply sorted/verified monotonic, binary search simply doesnβt apply.
- Requires random access (O(1) indexing) to be efficient β doesnβt work well on a plain linked list (no O(1) jump to the middle).
- Off-by-one bugs in boundary conditions (
<=vs<,midrounding) are notoriously easy to introduce β binary search has a well-earned reputation as βsimple in concept, easy to get subtly wrong in code.β
7. Real-World Applications
- Databases: Index lookups on sorted B-Tree pages internally use binary-search-like logic to find the right key within a node (see the Data Structures guide, Chapter 10).
- Search Engines: Locating a termβs postings list within a sorted term dictionary.
- Operating Systems: Finding a specific memory page or process ID within sorted kernel structures.
- Networking: IP routing table lookups often use binary-search-like structures over sorted prefix ranges.
- Finance: Binary search on the answer is common in algorithmic trading systems for finding threshold prices/quantities satisfying a constraint.
- Game Development: Collision detection systems sometimes binary-search along a sorted spatial axis.
- Compilers: Symbol table lookups in sorted structures, and binary-searching version/compatibility ranges.
- AI/ML: Hyperparameter search sometimes uses binary-search-on-the-answer when a metric is known to be monotonic in a parameter.
8. C++ Implementation
#include <iostream>
#include <vector>
// Classic binary search: return the index of target, or -1 if not found. O(log n).
int binarySearch(const std::vector<int>& arr, int target) {
int low = 0, high = static_cast<int>(arr.size()) - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // avoids overflow vs (low+high)/2 for large indices
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
low = mid + 1; // target must be in the right half
} else {
high = mid - 1; // target must be in the left half
}
}
return -1; // not found
}
// Lower Bound: first index where arr[i] >= target. O(log n).
int lowerBound(const std::vector<int>& arr, int target) {
int low = 0, high = static_cast<int>(arr.size()); // note: high starts at size(), not size()-1
while (low < high) {
int mid = low + (high - low) / 2;
if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid; // arr[mid] >= target β this could be the answer, so keep it in range
}
}
return low; // low == high, the first index where arr[i] >= target (or arr.size() if none)
}
// Upper Bound: first index where arr[i] > target. O(log n).
int upperBound(const std::vector<int>& arr, int target) {
int low = 0, high = static_cast<int>(arr.size());
while (low < high) {
int mid = low + (high - low) / 2;
if (arr[mid] <= target) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
// Binary Search on the Answer example: minimum "capacity" such that a monotonic
// predicate canAchieve(capacity) becomes true. O(log(range) * cost of predicate check).
// Here illustrated abstractly β canAchieve would be problem-specific.
int binarySearchOnAnswer(int lo, int hi, const std::function<bool(int)>& canAchieve) {
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (canAchieve(mid)) {
hi = mid; // mid works β try to do even better (smaller), keep mid in range
} else {
lo = mid + 1; // mid doesn't work β need a larger value
}
}
return lo; // smallest value for which canAchieve(value) is true
}
// Example usage
int main() {
std::vector<int> arr = {2, 5, 8, 12, 16, 23, 38, 45, 56, 72};
std::cout << "binarySearch(23): " << binarySearch(arr, 23) << "\n"; // 5
std::vector<int> withDupes = {2, 5, 5, 5, 8, 12};
std::cout << "lowerBound(5): " << lowerBound(withDupes, 5) << "\n"; // 1
std::cout << "upperBound(5): " << upperBound(withDupes, 5) << "\n"; // 4
return 0;
}
9. Code Walkthrough
mid = low + (high - low) / 2: This formula (rather than the seemingly-equivalent(low + high) / 2) avoids integer overflow whenlowandhighare both large β a classic, real-world bug (famously present in early binary search implementations, including in published textbooks) that only manifests for very large arrays.binarySearchβs loop conditionlow <= high: The<=(not<) is essential β whenlow == high, thereβs still exactly one element left to check; using<would incorrectly skip it.lowerBound/upperBoundβshigh = arr.size()(notsize()-1): These functions must be able to return βone past the endβ (meaning βtarget would belong after every existing elementβ) β startinghighatsize()(an otherwise-invalid index) is what allows that result to naturally fall out of the loop.lowerBoundβshigh = mid(notmid - 1) on a βkeepβ condition: Unlike classic binary search, heremiditself might be the answer, so we canβt exclude it β we narrowhighdown tomidrather thanmid - 1, and the loop continues untillow == highconverges on the exact boundary.binarySearchOnAnswerβs abstracted predicate: This function takes acanAchievepredicate as a parameter specifically to demonstrate that the shape of binary-search-on-the-answer is identical regardless of the underlying problem β only the predicate changes.
Common mistakes to watch for here:
- Using
(low + high) / 2and hitting overflow on very large arrays. - Using
<=vs<inconsistently between the loop condition and the boundary-update logic, causing infinite loops or off-by-one skips. - Forgetting that
lowerBound/upperBoundneedhighto start atsize(), notsize()-1.
10. Dry Run
lowerBound([2,5,5,5,8,12], target=5):
| Step | low | high | mid | arr[mid] | Condition | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 5 | 5 >= 5 β keep | high = 3 |
| 2 | 0 | 3 | 1 | 5 | 5 >= 5 β keep | high = 1 |
| 3 | 0 | 1 | 0 | 2 | 2 < 5 β too small | low = 1 |
| 4 | 1 | 1 | β | β | low == high, loop ends | return 1 |
Result: index 1 β the first occurrence of 5. β
11. Complexity Table
| Case | Time | Space |
|---|---|---|
| Best (target is the middle element) | O(1) | O(1) |
| Average | O(log n) | O(1) |
| Worst (target absent, or at a boundary) | O(log n) | O(1) |
Every entry explained: Best case is O(1) purely by luck (the very first mid check happens to match). Average and worst case are both O(log n) because binary searchβs halving behavior doesnβt depend on where the target is β even in the best-ΡΠ»ΡΡaΠΉ-excluded general case, youβre always doing the same halving work until either a match is found or the range is exhausted; thereβs no scenario (short of the lucky first guess) where fewer than ~logβ(n) comparisons are needed.
12. Common Mistakes
- Integer overflow in mid calculation (
(low+high)/2on huge arrays/index ranges). - Off-by-one errors in loop conditions and boundary updates β the single most common source of binary search bugs.
- Applying binary search to unsorted or non-monotonic data β silently gives wrong answers rather than crashing, which makes this mistake dangerous.
- Confusing βfoundβ binary search with boundary search β using the wrong template when the problem actually wants a lower/upper bound, not an exact match.
- Infinite loops from inconsistent update rules (e.g., setting
high = midwhen it should behigh = mid - 1, causing the range to never shrink).
13. Interview Questions
Conceptual:
- Why does binary search require sorted (or monotonic) data specifically?
- Prove that binary search is asymptotically optimal for comparison-based search β why canβt any comparison-based algorithm beat O(log n) in the worst case?
- Whatβs βbinary search on the answer,β and how do you recognize when a problem calls for it?
- Explain the difference between lower bound and upper bound, with an example involving duplicates.
- Why is
low + (high-low)/2preferred over(low+high)/2?
Coding:
- Implement binary search (iterative and recursive).
- Find the first and last occurrence of a target in a sorted array with duplicates.
- Search in a rotated sorted array.
- Find the peak element in a mountain array.
- Median of Two Sorted Arrays (binary search on the partition point β a hard but classic application).
- Capacity to Ship Packages Within D Days (binary search on the answer).
- Split Array Largest Sum (binary search on the answer).
Follow-ups / interviewer traps:
- βWhat if the array has duplicates β does plain binary search still find a valid index?β (yes, but not necessarily the first/last β thatβs what lower/upper bound solve)
- βCan you binary search on a rotated sorted array?β (yes, with modified comparison logic β tests deeper understanding beyond the textbook template)
- βYour solution uses recursion β whatβs the space complexity, and can you make it O(1)?β (tests awareness of the iterative conversion)
14. Practice Problems
Easy
- Binary Search (LeetCode 704)
- Search Insert Position (LeetCode 35)
- Sqrt(x) (LeetCode 69)
Medium
- Find First and Last Position of Element in Sorted Array (LeetCode 34)
- Search in Rotated Sorted Array (LeetCode 33)
- Find Peak Element (LeetCode 162)
- Koko Eating Bananas (LeetCode 875) β binary search on the answer
- Capacity To Ship Packages Within D Days (LeetCode 1011)
Hard
- Median of Two Sorted Arrays (LeetCode 4)
- Split Array Largest Sum (LeetCode 410)
- Find in Mountain Array (LeetCode 1095)
Also recommended: GeeksforGeeks βBinary Searchβ practice set, Codeforces problems tagged binary search (rating 1200-1700 for a good progression).
15. Summary
Key takeaways:
- Binary searchβs O(log n) is a direct mathematical consequence of βeach comparison eliminates at least half the remaining spaceβ β not an empirical rule to memorize.
- The precondition is monotonicity, not literally βsortednessβ β this generalization (binary search on the answer) unlocks a huge additional problem class beyond simple array search.
- Lower bound and upper bound are subtly different templates from exact-match search β know all three, and know which one a given problem actually needs.
Complexity recap:
| Time | Space | |
|---|---|---|
| Binary Search (any variant) | O(log n) | O(1) iterative |
Decision guide: Reach for binary search whenever data is sorted (or you can define a monotonic yes/no predicate) and you need to find a value, a boundary, or the optimal threshold of some parameter. If the data isnβt sorted and canβt cheaply be verified monotonic, look elsewhere (hashing for exact lookup, linear scan for one-off unsorted search).
Next chapter: 02_simple_sorts.md
Chapter 2: Simple Sorts (Bubble, Selection, Insertion)
Study time: ~4-5 hours | Prerequisite: Arrays, Big-O primer | Difficulty: Beginner
1. Introduction
Definition: Bubble Sort, Selection Sort, and Insertion Sort are the three canonical O(nΒ²) comparison-based sorting algorithms β each repeatedly compares and rearranges elements until the whole array is sorted, differing only in which comparisons/swaps they make and in what order.
Purpose: Not primarily to sort large real-world datasets (better algorithms exist for that β see Chapters 3-4) but to build the foundational intuition for loop invariants, in-place manipulation, and stability that every later, more sophisticated algorithm builds on.
Problem solved: Given an unordered array, produce a sorted array β these three algorithms solve it in the most direct, easy-to-verify-correct ways, at the cost of speed.
2. Intuition
- Bubble Sort: repeatedly scan the array, swapping any adjacent out-of-order pair. Each full pass βbubblesβ the largest remaining unsorted element to its correct position at the end β like carbonation bubbles naturally rising to the top of a glass, the largest values naturally rise to the end of the array with each pass.
- Selection Sort: repeatedly find the minimum of the remaining unsorted portion and swap it into place at the front. Itβs how a person might sort a hand of playing cards by repeatedly picking out βthe smallest card I havenβt placed yet.β
- Insertion Sort: build up a sorted portion one element at a time, inserting each new element into its correct position within the already-sorted portion β exactly how most people sort a hand of cards in real life: pick up a new card, slide it into the correct spot among the cards already in your sorted hand.
3. Step-by-Step Working
Bubble Sort on [5, 2, 8, 1, 9]:
Pass 1: compare adjacent pairs, swap if out of order.
(5,2)βswapβ[2,5,8,1,9] (5,8)βno swap (8,1)βswapβ[2,5,1,8,9] (8,9)βno swap
End of pass 1: [2,5,1,8,9] β largest element (9) is now bubbled to the end.
Pass 2: (2,5)βno swap (5,1)βswapβ[2,1,5,8,9] (5,8)βno swap (8,9 already placed, skip)
End of pass 2: [2,1,5,8,9]
Pass 3: (2,1)βswapβ[1,2,5,8,9] (2,5)βno swap
End of pass 3: [1,2,5,8,9] β sorted! (An optimization: if a pass makes ZERO swaps, the array is already sorted β stop early.)
Selection Sort on [5, 2, 8, 1, 9]:
Pass 1: find min of [5,2,8,1,9] β 1 (index 3). Swap with index 0 β [1,2,8,5,9]
Pass 2: find min of [2,8,5,9] (indices 1-4) β 2 (already at index 1, no swap needed) β [1,2,8,5,9]
Pass 3: find min of [8,5,9] (indices 2-4) β 5 (index 3). Swap with index 2 β [1,2,5,8,9]
Pass 4: find min of [8,9] (indices 3-4) β 8 (already in place) β [1,2,5,8,9] β sorted!
Insertion Sort on [5, 2, 8, 1, 9]:
Start: [5] is trivially sorted. Consider 2: insert into sorted portion β [2,5]
Consider 8: 8 > 5, stays at end β [2,5,8]
Consider 1: shift 8,5,2 right one each until correct spot found β [1,2,5,8]
Consider 9: 9 > 8, stays at end β [1,2,5,8,9] β sorted!
4. Complexity Analysis
Bubble Sort: each of the (n-1) passes does up to (n-1) comparisons β O(nΒ²) comparisons and swaps in the worst/average case. Best case (already sorted, with the early-exit optimization) is O(n) β a single pass detects zero swaps and stops immediately.
Selection Sort: always does exactly (n-1) + (n-2) + β¦ + 1 = O(nΒ²) comparisons, regardless of input order β thereβs no early-exit optimization possible, because finding the minimum of the remaining portion always requires scanning all of it. However, it does at most O(n) swaps (one per pass) β far fewer than Bubble Sortβs potentially O(nΒ²) swaps, which matters when swaps are expensive (e.g., large records, not just integers).
Insertion Sort: worst case (reverse-sorted input) requires shifting almost every element on almost every insertion β O(nΒ²). Best case (already sorted input) requires zero shifts β O(n), since every new element is immediately found to be in the correct place. This adaptivity (fast on nearly-sorted data) is Insertion Sortβs standout practical advantage.
Why all three are O(nΒ²) in general: each involves, in the worst case, comparing every pair of elements at least implicitly β with n elements, there are O(nΒ²) pairs, and none of these three algorithms has a mechanism (unlike Merge/Quick Sortβs divide-and-conquer) to avoid touching most of them.
5. Advantages
- Extremely simple to understand, implement, and verify correct β valuable for teaching and for tiny inputs where simplicity beats raw speed.
- All are in-place β O(1) extra space.
- Insertion Sort is genuinely fast (O(n)) on nearly-sorted data, and is used in practice as the base case for hybrid sorts (e.g., Timsort and introsort switch to insertion sort for small subarrays).
- Selection Sort minimizes the number of swaps β useful when writes are expensive (e.g., flash memory with limited write cycles).
6. Limitations
- O(nΒ²) makes all three impractical for large datasets (n > ~10,000 becomes noticeably slow; n > millions is essentially unusable).
- Bubble Sort is rarely used in practice even for teaching purposes beyond introducing the concept β itβs dominated by Insertion Sort in almost every practical respect (similar complexity, but Insertion Sort does less unnecessary work).
- Selection Sortβs O(nΒ²) comparisons happen unconditionally, even on already-sorted input β it has no adaptivity at all.
7. Real-World Applications
- Insertion Sort specifically: used as the base case in hybrid sorting algorithms (Timsort β Pythonβs and Javaβs default sort β switches to insertion sort for small runs; introsort, used in many C++ standard library implementations, does the same).
- Embedded/resource-constrained systems: for genuinely tiny, fixed-size datasets, the simplicity and low constant-factor overhead of these algorithms can beat asymptotically superior but more complex algorithms.
- Teaching/Education: foundational for understanding loop invariants, a skill that transfers directly to proving correctness of every later algorithm in this guide.
- Nearly-sorted data streams: Insertion Sortβs adaptivity makes it a reasonable choice for maintaining a mostly-sorted list that receives occasional new elements near the correct position (e.g., a live leaderboard with infrequent updates).
8. C++ Implementation
#include <iostream>
#include <vector>
// Bubble Sort with early-exit optimization. O(n) best case, O(nΒ²) worst case.
void bubbleSort(std::vector<int>& arr) {
int n = static_cast<int>(arr.size());
for (int i = 0; i < n - 1; ++i) {
bool swapped = false;
for (int j = 0; j < n - 1 - i; ++j) { // shrink the range each pass β the last i elements are already placed
if (arr[j] > arr[j + 1]) {
std::swap(arr[j], arr[j + 1]);
swapped = true;
}
}
if (!swapped) break; // no swaps this pass means the array is already fully sorted
}
}
// Selection Sort. Always O(nΒ²) comparisons, O(n) swaps.
void selectionSort(std::vector<int>& arr) {
int n = static_cast<int>(arr.size());
for (int i = 0; i < n - 1; ++i) {
int minIndex = i;
for (int j = i + 1; j < n; ++j) { // scan the remaining unsorted portion for the minimum
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
std::swap(arr[i], arr[minIndex]); // one swap per outer iteration, at most
}
}
}
// Insertion Sort. O(n) best case (nearly sorted), O(nΒ²) worst case.
void insertionSort(std::vector<int>& arr) {
int n = static_cast<int>(arr.size());
for (int i = 1; i < n; ++i) {
int key = arr[i]; // the element being inserted into the sorted portion
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j]; // shift larger elements one position right
j--;
}
arr[j + 1] = key; // place key in its correct position
}
}
// Example usage
int main() {
std::vector<int> a = {5, 2, 8, 1, 9};
std::vector<int> b = a, c = a;
bubbleSort(a);
selectionSort(b);
insertionSort(c);
auto print = [](const std::vector<int>& v) {
for (int x : v) std::cout << x << " ";
std::cout << "\n";
};
std::cout << "Bubble: "; print(a); // 1 2 5 8 9
std::cout << "Selection: "; print(b); // 1 2 5 8 9
std::cout << "Insertion: "; print(c); // 1 2 5 8 9
return 0;
}
9. Code Walkthrough
- Bubble Sortβs
n - 1 - iinner bound: Afteripasses, the lastielements are guaranteed already in their final sorted positions (each pass bubbles one more max element to the end) β so each subsequent pass can safely shrink its range, avoiding redundant comparisons against already-placed elements. - Bubble Sortβs
swappedflag: This is what gives Bubble Sort its O(n) best case β without it, the algorithm would blindly run all (n-1) passes even on already-sorted input. - Selection Sortβs
minIndextracking: Notice the swap only happens once per outer iteration, after the full inner scan completes β this is why Selection Sort does at most n-1 swaps total, dramatically fewer than Bubble Sortβs potentially O(nΒ²) swaps, even though both do O(nΒ²) comparisons. - Insertion Sortβs shift-then-place pattern: The
whileloop shifts elements right to make room, andarr[j+1] = keyplaces the element only after the correct position is found β this is structurally identical to how youβd manually insert a card into a sorted hand, sliding existing cards over one at a time.
Common mistakes to watch for here:
- Forgetting the early-exit optimization in Bubble Sort, losing its O(n) best case for free.
- In Selection Sort, swapping inside the inner loop instead of after it completes β this would perform far more swaps than necessary and technically changes the algorithmβs swap-count guarantee.
- In Insertion Sort, using
>=instead of>in the while condition β this subtle change affects stability (see summary section).
10. Dry Run
Insertion Sort on [5, 2, 8, 1, 9], traced index by index:
| i | key | Array before shifting | Shifts | Array after placing key |
|---|---|---|---|---|
| 1 | 2 | [5,2,8,1,9] | 5>2, shift 5 right | [2,5,8,1,9] |
| 2 | 8 | [2,5,8,1,9] | 8>5? no (5<8) β 0 shifts | [2,5,8,1,9] |
| 3 | 1 | [2,5,8,1,9] | 8>1 shift, 5>1 shift, 2>1 shift | [1,2,5,8,9] |
| 4 | 9 | [1,2,5,8,9] | 8>9? no β 0 shifts | [1,2,5,8,9] |
Final: [1,2,5,8,9] β sorted. β Notice how much work step 3 required (three shifts) versus step 2 and 4 (zero shifts) β this variability is exactly Insertion Sortβs adaptivity in action.
11. Complexity Table
| Algorithm | Best | Average | Worst | Space | Stable? | In-place? |
|---|---|---|---|---|---|---|
| Bubble Sort | O(n) | O(nΒ²) | O(nΒ²) | O(1) | Yes | Yes |
| Selection Sort | O(nΒ²) | O(nΒ²) | O(nΒ²) | O(1) | No* | Yes |
| Insertion Sort | O(n) | O(nΒ²) | O(nΒ²) | O(1) | Yes | Yes |
*Selection Sortβs standard swap-based implementation is not stable (swapping a minimum element past equal-valued elements can reorder them); a stable variant exists but requires shifting instead of swapping, sacrificing its βat most n swapsβ advantage.
Every entry explained: Bubble and Insertion Sort both achieve O(n) best case because they can detect βnothing more to doβ (zero swaps, or zero shifts needed) and stop early on already-sorted input. Selection Sort cannot β finding the minimum of the remaining portion always requires a full scan, regardless of whether that portion happens to already be in order, so its best case is no better than its worst case.
12. Common Mistakes
- Forgetting Bubble Sortβs early-exit check, losing adaptivity for free.
- Off-by-one in loop bounds β a very common source of bugs across all three (e.g., iterating one index too far and reading out of bounds).
- Swapping instead of shifting in Insertion Sort β technically works but performs three assignments per shift instead of one, a real (if small) performance difference.
- Assuming Selection Sort is stable β the standard swap-based version is not; this can matter when sorting records by one field while wanting to preserve relative order of another.
- Using these algorithms on large datasets in production code β always reach for Merge/Quick/Heap Sort (or the standard libraryβs sort) beyond small n.
13. Interview Questions
Conceptual:
- Why is Insertion Sort adaptive (fast on nearly-sorted data) while Selection Sort is not?
- Why does Selection Sort do fewer swaps than Bubble Sort, and when would that matter?
- Explain what βstableβ means for a sorting algorithm, and why Selection Sortβs standard implementation isnβt stable.
- Why are these algorithms still taught/used despite being asymptotically worse than Merge/Quick Sort?
- How do hybrid sorting algorithms (Timsort, introsort) use Insertion Sort as a component?
Coding:
- Implement all three sorts from scratch.
- Modify Selection Sort to be stable.
- Sort a nearly-sorted array (each element at most k positions from its sorted position) optimally β Insertion Sort with a heap can achieve O(n log k).
- Count the number of swaps Bubble Sort would perform (related to counting inversions).
Follow-ups / interviewer traps:
- βCan you sort in O(n log k) if each element is at most k positions from its final sorted spot?β (tests recognizing a heap-based hybrid approach, connecting back to the Data Structures guideβs Heap chapter)
- βWhatβs the minimum number of swaps to sort an array?β (a different, cycle-decomposition-based problem β tests whether the candidate conflates βsorting algorithm swap countβ with βminimum possible swapsβ)
14. Practice Problems
Easy
- Sort an Array (LeetCode 912) β use as a testbed to implement and compare all three
- Insertion Sort List (LeetCode 147) β linked list variant
Medium
- Minimum Number of Swaps to Sort an Array (related concept, GeeksforGeeks)
- Sort Colors (LeetCode 75) β related partitioning idea, though solved more elegantly with a specialized approach
Hard
- Count Inversions in an Array (naturally solved by a modified merge sort β foreshadows Chapter 3)
Also recommended: GeeksforGeeks βSorting Algorithmsβ practice set for implementation drills.
15. Summary
Key takeaways:
- All three are O(nΒ²) in general, differing mainly in adaptivity (Bubble and Insertion can exploit partial order; Selection cannot) and swap count (Selection does the fewest).
- Insertion Sort is the most practically useful of the three β genuinely fast on nearly-sorted data and used as a component in real-world hybrid sorting algorithms.
- These algorithms exist primarily to build intuition (loop invariants, in-place manipulation, stability) that transfers directly to understanding Merge Sort and Quick Sort next.
Complexity recap:
| Best | Worst | Space | Stable | |
|---|---|---|---|---|
| Bubble | O(n) | O(nΒ²) | O(1) | Yes |
| Selection | O(nΒ²) | O(nΒ²) | O(1) | No |
| Insertion | O(n) | O(nΒ²) | O(1) | Yes |
Decision guide: Use Insertion Sort for small arrays or nearly-sorted data (or as a component within a larger hybrid sort). Use Selection Sort only when minimizing writes specifically matters more than comparison count. Avoid Bubble Sort in production code entirely β Insertion Sort dominates it in essentially every practical respect. For anything beyond small/nearly-sorted inputs, move on to Merge Sort or Quick Sort (next chapters).
Next chapter: 03_merge_sort.md
Chapter 3: Merge Sort
Study time: ~5-6 hours | Prerequisite: Recursion, Simple Sorts (Ch. 2) | Difficulty: Intermediate
1. Introduction
Definition: Merge Sort is a divide-and-conquer sorting algorithm: recursively split the array in half until each piece has one element (trivially sorted), then repeatedly merge sorted pieces back together into larger sorted pieces until the whole array is sorted.
Purpose: To guarantee O(n log n) sorting performance β no worst-case degradation, unlike Quick Sort β at the cost of extra memory.
Problem solved: Sorting with a guaranteed time bound, and with stability (equal elements retain their relative order) β both properties matter in real systems (e.g., sorting by one field after already having sorted by another, or real-time systems that canβt tolerate Quick Sortβs rare O(nΒ²) worst case).
2. Intuition
If you have two already-sorted piles of cards, merging them into one sorted pile is easy and fast: repeatedly compare the top cards of each pile, take the smaller, and repeat β this is O(n) for two piles totaling n cards, since each comparison βconsumesβ exactly one card. Merge Sortβs insight is to manufacture those two sorted piles by recursively applying the same idea: a pile of 1 card is trivially βsorted,β so you can always get down to piles small enough to be sorted for free, then merge your way back up.
This is the classic divide-and-conquer pattern: divide the problem into smaller subproblems of the same type, solve them (recursively, down to a trivial base case), then combine the subproblem solutions into a solution for the original problem.
3. Step-by-Step Working
Sorting [38, 27, 43, 3, 9, 82, 10]:
DIVIDE (recursively split in half until single elements):
[38,27,43,3,9,82,10]
/ \
[38,27,43,3] [9,82,10]
/ \ / \
[38,27] [43,3] [9,82] [10]
/ \ / \ / \
[38][27] [43][3] [9][82]
CONQUER/COMBINE (merge sorted pairs back up):
[38]+[27] β merge β [27,38]
[43]+[3] β merge β [3,43]
[9]+[82] β merge β [9,82]
[10] stays as-is (odd one out at this level)
[27,38]+[3,43] β merge β [3,27,38,43]
[9,82]+[10] β merge β [9,10,82]
[3,27,38,43]+[9,10,82] β merge β [3,9,10,27,38,43,82] β FINAL SORTED ARRAY
The merge step itself, merging [3,27,38,43] and [9,10,82]:
Pointers: i=0 (left), j=0 (right). Compare left[0]=3 vs right[0]=9 β 3 smaller β take 3, i=1
Compare left[1]=27 vs right[0]=9 β 9 smaller β take 9, j=1
Compare left[1]=27 vs right[1]=10 β 10 smaller β take 10, j=2
Compare left[1]=27 vs right[2]=82 β 27 smaller β take 27, i=2
Compare left[2]=38 vs right[2]=82 β 38 smaller β take 38, i=3
Compare left[3]=43 vs right[2]=82 β 43 smaller β take 43, i=4 (left exhausted)
Left exhausted β copy remaining right elements directly: 82
Result: [3,9,10,27,38,43,82]
4. Complexity Analysis
Time: O(n log n), guaranteed in ALL cases (best, average, worst).
The recursion splits the array in half at each level, producing logβ(n) levels of recursion (this is identical reasoning to Binary Searchβs O(log n): repeatedly halving n until you reach 1 takes logβ(n) steps). At each level, the total work across all the merges at that level is O(n) β every element gets touched exactly once per level during merging, regardless of how many pieces that level has been split into. Total work = (number of levels) Γ (work per level) = O(log n) Γ O(n) = O(n log n).
Why itβs guaranteed, unlike Quick Sort: Merge Sortβs split is always exactly even (or as even as integer division allows) β it never depends on the dataβs actual values, unlike Quick Sortβs pivot-dependent partitioning. This is precisely why Merge Sort has no bad-input vulnerability.
Space: O(n) extra β the merge step needs a temporary array to hold merged results (you canβt merge two adjacent sorted subarrays purely in-place without either extra space or a much more complex, slower algorithm) β this is Merge Sortβs main practical drawback versus Quick Sortβs O(log n).
5. Advantages
- Guaranteed O(n log n) in every case β no adversarial input can degrade it, unlike Quick Sort.
- Stable β equal elements retain their original relative order, which matters for multi-key sorting and certain application-level correctness requirements.
- Naturally parallelizable β independent subarrays can be sorted concurrently on separate threads/cores before merging.
- Works well for external sorting (data too large to fit in memory) β merging sorted runs from disk is exactly what Merge Sortβs core operation does, and it doesnβt require random access to the whole dataset the way Quick Sortβs partitioning does.
6. Limitations
- O(n) extra space β a real cost for very large datasets, and a genuine disadvantage versus in-place alternatives.
- Slightly slower in practice than a well-implemented Quick Sort on typical (non-adversarial) data, due to the overhead of allocating/copying the temporary merge array.
- Not in-place (standard implementation) β some specialized in-place merge sort variants exist, but theyβre significantly more complex and usually slower in practice than the extra-space version.
7. Real-World Applications
- External Sorting: Sorting datasets too large for RAM (database sort operations, large file sorting) β Merge Sortβs sequential-access merge pattern is ideal for disk I/O, unlike Quick Sortβs random-access partitioning.
- Standard Library Sorts: Javaβs
Arrays.sort()for objects (not primitives) uses a variant of merge sort (Timsort, which is fundamentally merge-sort-based) specifically because stability matters for sorting objects by a field. - Databases: Merge joins and external sort-merge operations in query execution engines.
- Linked Lists: Merge Sort is the preferred sort for linked lists specifically, since it doesnβt need random access (unlike Quick Sort, which relies on it for efficient partitioning) β merging two sorted linked lists is a natural O(n) pointer-relinking operation.
- Version Control / Diff Tools: Merging sorted change sets uses the same underlying merge logic.
- Distributed Systems: MapReduce-style sorting of massive distributed datasets fundamentally relies on the same divide-conquer-merge structure.
8. C++ Implementation
#include <iostream>
#include <vector>
// Merge two sorted subarrays arr[left..mid] and arr[mid+1..right] into one sorted range.
void merge(std::vector<int>& arr, int left, int mid, int right) {
std::vector<int> leftPart(arr.begin() + left, arr.begin() + mid + 1);
std::vector<int> rightPart(arr.begin() + mid + 1, arr.begin() + right + 1);
int i = 0, j = 0, k = left;
// Merge while both subarrays still have elements β always take the smaller front element.
while (i < static_cast<int>(leftPart.size()) && j < static_cast<int>(rightPart.size())) {
if (leftPart[i] <= rightPart[j]) { // <= (not <) preserves stability for equal elements
arr[k++] = leftPart[i++];
} else {
arr[k++] = rightPart[j++];
}
}
// Copy any remaining elements β at most one of these loops does any work.
while (i < static_cast<int>(leftPart.size())) arr[k++] = leftPart[i++];
while (j < static_cast<int>(rightPart.size())) arr[k++] = rightPart[j++];
}
// Recursively divide, then merge on the way back up. O(n log n).
void mergeSort(std::vector<int>& arr, int left, int right) {
if (left >= right) return; // base case: 0 or 1 element is trivially sorted
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid); // sort left half
mergeSort(arr, mid + 1, right); // sort right half
merge(arr, left, mid, right); // combine the two sorted halves
}
// Example usage
int main() {
std::vector<int> arr = {38, 27, 43, 3, 9, 82, 10};
mergeSort(arr, 0, static_cast<int>(arr.size()) - 1);
for (int x : arr) std::cout << x << " ";
std::cout << "\n"; // 3 9 10 27 38 43 82
return 0;
}
9. Code Walkthrough
mergeβs temporary vectorsleftPart/rightPart: Copying both halves out first is what makes the merge itself simple and correct β trying to merge two adjacent ranges of the same array in-place without a copy is surprisingly tricky (you risk overwriting values you still need to read), which is exactly why Merge Sortβs standard form isnβt in-place.leftPart[i] <= rightPart[j](using<=, not<): This is the specific detail that makes Merge Sort stable β when elements are equal, always preferring the left subarrayβs element (which, due to the recursive structure, always originated from an earlier position in the original array) preserves their original relative order.- The two trailing
whileloops: Only one of them ever actually executes any iterations (whichever subarray still has leftover elements after the main merge loop exits) β but writing both is necessary since you donβt know in advance which one will have leftovers. mergeSortβs base caseleft >= right: Handles both the 0-element case (left > right, shouldnβt normally occur but is a safe guard) and the 1-element case (left == right) β both are trivially βalready sorted,β requiring no work.- Recursing on both halves BEFORE merging: This ordering (divide fully, then combine on the way back up) is the defining structure of divide-and-conquer β contrast this with Quick Sort (next chapter), which does its βcombine-equivalentβ work (partitioning) before recursing, not after.
Common mistakes to watch for here:
- Using
<instead of<=in the merge comparison, silently breaking stability. - Off-by-one errors in the
midcalculation or the subarray boundary indices passed to recursive calls. - Forgetting either of the two trailing copy loops, losing leftover elements from whichever subarray wasnβt fully consumed by the main merge loop.
10. Dry Run
Already traced in full in section 3 β the recursive split down to [38], [27], [43], [3], [9], [82], [10], then merged back up level by level to [3,9,10,27,38,43,82]. The key detail worth re-emphasizing: the merge step at the top level (merging [3,27,38,43] with [9,10,82]) does exactly 6 comparisons to interleave 7 elements β each comparison βconsumesβ one element into the output, so the merge cost is linear in the combined size of the two halves being merged, consistent with the O(n) per-level claim from section 4.
11. Complexity Table
| Case | Time | Space |
|---|---|---|
| Best | O(n log n) | O(n) |
| Average | O(n log n) | O(n) |
| Worst | O(n log n) | O(n) |
Every entry explained: All three cases are identical because Merge Sortβs split is always balanced (roughly n/2 and n/2) regardless of the input dataβs actual values β unlike Quick Sort, where an adversarial input can force wildly unbalanced splits. There is no βluckyβ or βunluckyβ input for Merge Sortβs time complexity; the O(n) extra space is likewise constant across all cases, since the temporary merge bufferβs size only depends on the subarray length being merged, never on data values.
12. Common Mistakes
- Breaking stability by using
<instead of<=in the merge comparison. - Off-by-one errors in computing
midor in the subarray ranges passed to recursive calls β extremely common, and worth carefully tracing through a small example (as in section 10) whenever debugging. - Forgetting to copy leftover elements from whichever subarray wasnβt fully drained during the main merge loop.
- Assuming Merge Sort is in-place β it fundamentally requires O(n) extra space in its standard form; donβt claim O(1) space in an interview without discussing the significantly more complex in-place variants.
- Unnecessary re-allocation of temporary vectors on every single merge call in performance-sensitive code β a well-optimized implementation allocates one reusable buffer once, rather than a fresh vector on every recursive merge call.
13. Interview Questions
Conceptual:
- Why is Merge Sortβs time complexity guaranteed O(n log n) in all cases, unlike Quick Sort?
- Explain why Merge Sort is stable and Quick Sort (standard implementation) is not.
- Why does Merge Sort require O(n) extra space β can you avoid it?
- Why is Merge Sort preferred for sorting linked lists specifically?
- How would you parallelize Merge Sort across multiple threads/cores?
Coding:
- Implement Merge Sort (array and linked list versions).
- Count Inversions in an array using a modified merge step (an inversion is counted every time a right-subarray element is taken before a left-subarray element during merge).
- Merge k Sorted Lists (generalizes the two-way merge to k-way β connects back to the Heap chapter in the Data Structures guide).
- Sort a linked list in O(n log n) using merge sort.
- External sort simulation: sort a dataset too large for memory using disk-based merge passes.
Follow-ups / interviewer traps:
- βCan you reduce the space complexity to O(1)?β (possible but significantly more complex and generally slower in practice β expects awareness that this is a real but rarely-used technique, not a simple tweak)
- βHow does counting inversions relate to merge sort?β (tests recognizing that the merge stepβs βtake from right before left is exhaustedβ moments are exactly the inversions β a beautiful, non-obvious connection worth knowing cold)
- βMerge k sorted lists β how does your approachβs complexity compare to repeatedly merging two at a time?β (tests understanding that a heap-based k-way merge, O(N log k), beats naive repeated pairwise merging, O(NΒ·k))
14. Practice Problems
Easy
- Merge Sorted Array (LeetCode 88) β related merge logic, different setup
Medium
- Sort an Array (LeetCode 912) β implement and benchmark against Chapter 2βs sorts
- Sort List (LeetCode 148) β linked list merge sort
- Count of Smaller Numbers After Self (LeetCode 315) β solvable via modified merge sort
Hard
- Reverse Pairs (LeetCode 493) β modified merge sort counting a different condition
- Merge k Sorted Lists (LeetCode 23)
- Count of Range Sum (LeetCode 327)
Also recommended: implement Count Inversions and verify your count against a brute-force O(nΒ²) double-loop on small test cases β an excellent correctness-check exercise.
15. Summary
Key takeaways:
- Merge Sort is the textbook example of divide-and-conquer: divide until trivial, conquer (merge) on the way back up.
- Its O(n log n) is guaranteed, not average-case, because the split is always balanced regardless of input values β the opposite of Quick Sortβs data-dependent partitioning.
- Stability and guaranteed worst-case performance are Merge Sortβs headline advantages; O(n) extra space is its main cost.
Complexity recap:
| Time (all cases) | Space | Stable | |
|---|---|---|---|
| Merge Sort | O(n log n) | O(n) | Yes |
Decision guide: Choose Merge Sort when you need guaranteed worst-case performance (real-time systems, adversarial-input contexts), stability (multi-key sorting), or youβre sorting a linked list (no random access needed) or external/disk-resident data. If memory is tight and average-case performance is acceptable, Quick Sort (next chapter) is usually the faster practical choice.
Next chapter: 04_quick_sort.md
Chapter 4: Quick Sort
Study time: ~5-6 hours | Prerequisite: Recursion, Merge Sort (Ch. 3) | Difficulty: Intermediate
1. Introduction
Definition: Quick Sort is a divide-and-conquer sorting algorithm that picks a pivot element, partitions the array so everything smaller than the pivot ends up to its left and everything larger ends up to its right (with the pivot now in its final sorted position), then recursively sorts the two partitions.
Purpose: To sort in-place with excellent average-case performance and the best practical constant factors of any general-purpose comparison sort β itβs the algorithm most standard librariesβ sort() functions are built around (often as part of a hybrid like introsort).
Problem solved: Fast, memory-efficient (in-place) general-purpose sorting, when average-case O(n log n) is acceptable and worst-case O(nΒ²) can be avoided or mitigated through good pivot selection.
2. Intuition
Imagine sorting a shelf of books by picking one book at random (the pivot), then physically moving every book that belongs before it to the left of it, and every book that belongs after it to the right β after this single pass, that pivot book is guaranteed to be in its final correct position, even though nothing else is fully sorted yet. Now you have two smaller, independent shelves to sort the same way β recursively. This is the core insight: unlike Merge Sort (which does its βhard workβ after recursing, during merge), Quick Sort does its hard work before recursing (during partition), and the recursion itself requires no combining step at all β once both halves are individually sorted, the whole array is automatically sorted, because the partition step already guaranteed the correct relative ordering between the two halves.
3. Step-by-Step Working
Sorting [10, 80, 30, 90, 40, 50, 70] using the last element as pivot (Lomuto partition scheme):
Initial: [10, 80, 30, 90, 40, 50, 70] pivot = 70 (last element)
Partition pass: maintain a boundary `i` for "everything β€ pivot goes here or before."
j=0: arr[0]=10 β€ 70 β i=0, swap arr[0] with arr[0] (no-op) β [10,80,30,90,40,50,70]
j=1: arr[1]=80 > 70 β skip
j=2: arr[2]=30 β€ 70 β i=1, swap arr[1] with arr[2] β [10,30,80,90,40,50,70]
j=3: arr[3]=90 > 70 β skip
j=4: arr[4]=40 β€ 70 β i=2, swap arr[2] with arr[4] β [10,30,40,90,80,50,70]
j=5: arr[5]=50 β€ 70 β i=3, swap arr[3] with arr[5] β [10,30,40,50,80,90,70]
(j=6 is the pivot itself, stop)
Finally, swap pivot (index 6) with i+1=4 β [10,30,40,50,70,90,80]
Pivot (70) is now at index 4 β its FINAL correct position, guaranteed.
Left partition: [10,30,40,50] (all β€ 70)
Right partition: [90,80] (all > 70)
Recursively quick-sort each partition the same way:
[10,30,40,50] β already sorted after its own partitioning steps
[90,80] β pivot 80, partition β [80,90]
Final merged-by-position result: [10,30,40,50,70,80,90]
The critical insight: unlike Merge Sort, thereβs no separate βcombineβ step at the end β once both partitions are individually sorted in-place, the whole array is automatically sorted, because the partition step already guaranteed every element in the left partition is β€ the pivot and every element in the right partition is > the pivot.
4. Complexity Analysis
Time: O(n log n) average, O(nΒ²) worst case.
Average case reasoning: if the pivot reasonably splits the array (even a consistently 25%/75% split, not just perfect 50/50), the recursion depth is O(log n), and each level does O(n) total partitioning work β giving O(n log n), the same fundamental reasoning as Merge Sortβs complexity derivation.
Worst case reasoning: if the pivot is always the smallest or largest remaining element (e.g., naively picking the first or last element as pivot on an already-sorted or reverse-sorted array), each partition step only removes one element from consideration, requiring n, then n-1, then n-2, β¦ levels of recursion β O(n) levels instead of O(log n), each still doing O(n) partitioning work, giving O(nΒ²) total. This is exactly analogous to a plain BST degenerating into a linked list when built from sorted input (Data Structures guide, Chapter 7) β an unlucky/adversarial choice removes the βbalanced halvingβ that the algorithmβs good performance depends on.
Mitigating the worst case: randomized pivot selection (pick a uniformly random element as pivot before partitioning) makes the worst case astronomically unlikely for any fixed input, since an adversary canβt predict which element will be chosen β this single change is what makes Quick Sort practically reliable despite its theoretical O(nΒ²) worst case. The median-of-three heuristic (use the median of the first, middle, and last elements as the pivot) is another common, cheap mitigation.
Space: O(log n) average (recursion stack for a balanced split), O(n) worst case (recursion stack for a maximally unbalanced split) β this is genuinely in-place in the sense of not needing an auxiliary array like Merge Sort, but the recursion stack itself is real (if usually small) extra space.
5. Advantages
- Excellent average-case performance, and the best practical constant factors of any general-purpose comparison sort β usually faster in wall-clock time than Merge Sort on typical data, due to better cache locality (in-place partitioning touches memory more predictably) and no allocation overhead.
- In-place (O(log n) auxiliary space for the recursion stack, versus Merge Sortβs O(n)).
- Easily randomized to make worst-case behavior practically negligible.
6. Limitations
- O(nΒ²) worst case is real β without randomization or a good pivot heuristic, adversarial or already-sorted/reverse-sorted input can trigger it.
- Not stable (standard implementation) β partitioning can reorder equal elements relative to each other.
- More implementation care needed than Merge Sort to get right (partition scheme edge cases β duplicate-heavy arrays, in particular, can degrade a naive implementationβs performance without special handling like a three-way partition).
7. Real-World Applications
- Standard Library Sorts: C++βs
std::sortis typically implemented as introsort β Quick Sort with a fallback to Heap Sort if recursion depth gets suspiciously large (signaling a potential worst-case scenario), combined with Insertion Sort for small subarrays. This hybrid is specifically designed to capture Quick Sortβs excellent average performance while eliminating its worst-case risk. - Databases: In-memory sort operations (when data fits in RAM, unlike Merge Sortβs external-sort use case) commonly use quicksort-family algorithms.
- Operating Systems: Various kernel-level sorting tasks where memory efficiency (in-place) matters.
- Competitive Programming: The default general-purpose sort choice whenever stability isnβt required and data fits in memory.
- Graphics/Game Development: Sorting objects by depth/z-order for rendering, where speed matters more than stability.
8. C++ Implementation
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
// Lomuto partition scheme: places pivot (last element) in its final position,
// returns that final index. Everything β€ pivot ends up to its left.
int partition(std::vector<int>& arr, int low, int high) {
int pivot = arr[high];
int i = low - 1; // boundary: everything at index <= i is confirmed <= pivot
for (int j = low; j < high; ++j) {
if (arr[j] <= pivot) {
i++;
std::swap(arr[i], arr[j]);
}
}
std::swap(arr[i + 1], arr[high]); // place the pivot in its final position
return i + 1;
}
// Randomized pivot selection: swap a random element into the pivot position BEFORE
// partitioning β this is what makes worst-case O(nΒ²) practically negligible.
int randomizedPartition(std::vector<int>& arr, int low, int high) {
int randomIndex = low + rand() % (high - low + 1);
std::swap(arr[randomIndex], arr[high]); // move random element to the pivot slot
return partition(arr, low, high);
}
void quickSort(std::vector<int>& arr, int low, int high) {
if (low >= high) return; // base case: 0 or 1 element is trivially sorted
int pivotIndex = randomizedPartition(arr, low, high);
quickSort(arr, low, pivotIndex - 1); // recursively sort left partition
quickSort(arr, pivotIndex + 1, high); // recursively sort right partition
}
// Example usage
int main() {
std::srand(static_cast<unsigned>(std::time(nullptr)));
std::vector<int> arr = {10, 80, 30, 90, 40, 50, 70};
quickSort(arr, 0, static_cast<int>(arr.size()) - 1);
for (int x : arr) std::cout << x << " ";
std::cout << "\n"; // 10 30 40 50 70 80 90
return 0;
}
9. Code Walkthrough
partitionβs boundary variablei: Everything at index<= iis confirmed to be<= pivotβ the loop invariant this algorithm maintains throughout. Each timearr[j] <= pivotis found,iadvances by one and the two elements swap, extending the βconfirmed smallβ region by exactly one.- The final swap
arr[i+1]witharr[high]: This places the pivot (which sat atarr[high]throughout the scan) into its correct final position β right after the last confirmed-small element, which is exactly where it belongs. randomizedPartitionβs pre-swap: By swapping a uniformly random element into the pivot slot before calling the ordinarypartition, we ensure the pivot used is effectively random β without changingpartitionβs logic at all. This is a clean, minimal way to add randomization to any existing Lomuto-style partition implementation.quickSortβs recursive structure: Unlike Merge Sort, thereβs no work done after the two recursive calls β partitioning (the βhard workβ) happens before recursing, and once both partitions are individually sorted, the array is automatically fully sorted with no combine step needed.
Common mistakes to watch for here:
- Forgetting randomization (or another pivot-selection safeguard) entirely, leaving the implementation vulnerable to O(nΒ²) on sorted/reverse-sorted or adversarially-crafted input.
- Off-by-one errors in the partition boundary logic β a very common source of subtle bugs, especially around the final pivot-placing swap.
- Not handling duplicate-heavy arrays well β the standard two-way partition shown here can still degrade toward O(nΒ²)-like behavior on arrays with many equal elements; a three-way partition (Dutch National Flag style) fixes this specific case.
10. Dry Run
Traced in full in section 3: pivot 70 correctly lands at index 4 after one partition pass, splitting into [10,30,40,50] and [90,80], each recursively sorted the same way, converging on [10,30,40,50,70,80,90].
Partition pass trace, condensed:
| j | arr[j] | β€ pivot(70)? | i after | Array state |
|---|---|---|---|---|
| 0 | 10 | yes | 0 | [10,80,30,90,40,50,70] |
| 1 | 80 | no | 0 | unchanged |
| 2 | 30 | yes | 1 | [10,30,80,90,40,50,70] |
| 3 | 90 | no | 1 | unchanged |
| 4 | 40 | yes | 2 | [10,30,40,90,80,50,70] |
| 5 | 50 | yes | 3 | [10,30,40,50,80,90,70] |
| final swap | β | β | β | swap i+1=4 with high=6 β [10,30,40,50,70,90,80] |
Pivot 70 lands at index 4 β correctly separating everything β€70 (left) from everything >70 (right). β
11. Complexity Table
| Case | Time | Space | Cause |
|---|---|---|---|
| Best | O(n log n) | O(log n) | Pivot always splits roughly evenly |
| Average | O(n log n) | O(log n) | Random/typical data gives reasonably balanced splits on average |
| Worst | O(nΒ²) | O(n) | Pivot always the min/max of the remaining range (e.g., naive pivot on sorted input) |
Every entry explained: The best and average cases coincide at O(n log n) because βreasonably balancedβ splits (even far from perfectly 50/50) are enough to keep recursion depth at O(log n) β the argument doesnβt require exact halving, just splits that shrink geometrically. The worst case arises specifically when the pivot choice is maximally unlucky at every single level, turning geometric shrinkage into linear shrinkage (n, n-1, n-2, β¦) β randomization makes this scenarioβs probability vanishingly small for any fixed adversarial input, though it remains theoretically possible.
12. Common Mistakes
- Not randomizing (or otherwise safeguarding) pivot selection β leaves the implementation vulnerable to real, exploitable O(nΒ²) worst-case behavior on common inputs like sorted or reverse-sorted arrays.
- Off-by-one errors in partition boundaries β extremely common; always trace through a small example by hand when debugging.
- Assuming Quick Sort is stable β it is not, in its standard form; donβt claim this in an interview without qualification.
- Poor performance on duplicate-heavy arrays without a three-way partition β a common interview follow-up probes exactly this weakness.
- Confusing average-case and worst-case complexity when discussing Quick Sortβs guarantees β always be explicit about which case youβre describing.
13. Interview Questions
Conceptual:
- Why is Quick Sortβs worst case O(nΒ²), and what specific inputs trigger it for a naive (unrandomized) implementation?
- Why does randomizing pivot selection make the worst case practically negligible without changing its theoretical existence?
- Compare Quick Sort and Merge Sort β when would you choose each?
- Why isnβt standard Quick Sort stable, and does that ever matter in practice?
- What is introsort, and why do many standard libraries use it instead of pure Quick Sort?
Coding:
- Implement Quick Sort with randomized pivot selection.
- Implement a three-way partition (Dutch National Flag) to handle duplicate-heavy arrays efficiently.
- Find the Kth largest/smallest element using Quickselect (a Quick-Sort-partition-based selection algorithm, average O(n)).
- Sort an array of 0s, 1s, and 2s in one pass (Dutch National Flag problem directly).
- Implement Quick Sort iteratively (using an explicit stack instead of recursion).
Follow-ups / interviewer traps:
- βCan you find the Kth largest element without fully sorting the array?β (expects Quickselect, average O(n), a direct and very common application of Quick Sortβs partition step alone)
- βYour Quick Sort is slow on an array of all identical elements β why, and how do you fix it?β (tests awareness of the duplicate-heavy degradation and the three-way-partition fix)
- βWhatβs the actual worst-case space complexity, and how does tail-call/smaller-first recursion help?β (tests knowledge that recursing into the smaller partition first, and looping for the larger one, bounds stack depth to O(log n) even in cases that would otherwise risk O(n))
14. Practice Problems
Easy
- Sort Colors (LeetCode 75) β Dutch National Flag / 3-way partition
Medium
- Sort an Array (LeetCode 912) β benchmark against Merge Sort
- Kth Largest Element in an Array (LeetCode 215) β Quickselect application
- Sort List (compare Quick Sortβs poor fit for linked lists against Merge Sortβs natural fit)
Hard
- Median of Two Sorted Arrays (LeetCode 4) β partition-based thinking, related in spirit
- Wiggle Sort II (LeetCode 324) β uses a Quickselect-based median-finding step
Also recommended: benchmark your Quick Sort against Merge Sort on random, sorted, reverse-sorted, and duplicate-heavy inputs β directly observe the worst-case behavior and how randomization/three-way partitioning fixes it.
15. Summary
Key takeaways:
- Quick Sort does its βhard workβ (partitioning) before recursing, unlike Merge Sortβs βhard work after recursingβ (merging) β this is the fundamental structural difference between the two.
- O(n log n) average case comes from geometrically-shrinking partition sizes; O(nΒ²) worst case comes from a maximally unlucky pivot at every level, mitigated almost entirely in practice by randomization.
- In-place with excellent real-world constant factors makes it the default choice for general in-memory sorting when stability isnβt required.
Complexity recap:
| Best | Average | Worst | Space | Stable | |
|---|---|---|---|---|---|
| Quick Sort | O(n log n) | O(n log n) | O(nΒ²) | O(log n) avg | No |
Decision guide: Choose Quick Sort (or trust your languageβs built-in sort, which is often introsort/Quick-Sort-based) for general-purpose in-memory sorting when average-case performance and memory efficiency matter more than worst-case guarantees or stability. Choose Merge Sort instead when you need guaranteed worst-case performance, stability, or youβre sorting a linked list or external/disk-resident data.
Next chapter: 05_heap_sort.md
Chapter 5: Heap Sort
Study time: ~4-5 hours | Prerequisite: Heaps (Data Structures guide, Ch. 5) | Difficulty: Intermediate
1. Introduction
Definition: Heap Sort sorts an array by first rearranging it into a Max-Heap (in-place, using the array itself as the heapβs backing storage β see the Data Structures guideβs Heap chapter for the underlying structure), then repeatedly extracting the maximum (always at the root) and placing it at the end of the unsorted region, shrinking the heap by one each time.
Purpose: To combine Quick Sortβs in-place, O(1)-extra-space property with Merge Sortβs guaranteed-worst-case O(n log n) β Heap Sort is the algorithm that achieves both simultaneously, at the cost of losing stability and having noticeably worse real-world constant factors (cache locality) than either.
Problem solved: Sorting when you need a guaranteed O(n log n) bound and O(1) extra space β exactly the gap between Merge Sort (guaranteed time, but O(n) space) and Quick Sort (O(log n) space, but no time guarantee).
2. Intuition
If you have a Max-Heap (Data Structures guide, Chapter 5), you already know its root is always the maximum element, retrievable in O(1), with removal costing O(log n) (sift-down). If you repeatedly remove the max and place it at the end of a shrinking βunsortedβ region, you naturally build up a sorted array from the back to the front β this is Heap Sortβs entire idea, and it reuses 100% of the Heap chapterβs machinery, just applied for a new purpose (sorting, rather than priority-queue access).
The clever part is doing this in-place: rather than using a separate heap data structure, treat the array itself as the heapβs backing array (exactly the array-representation trick from the Heap chapter), and use the βshrinking unsorted region / growing sorted region at the endβ idea to avoid needing any extra memory at all.
3. Step-by-Step Working
Sorting [4, 10, 3, 5, 1]:
STEP 1 β Build a Max-Heap in-place from the unsorted array (this is exactly the O(n)
"build-heap via bottom-up sift-down" technique from the Data Structures guide, Ch.5):
[4, 10, 3, 5, 1] β after build-heap β [10, 5, 3, 4, 1]
(Verify: parent(10) has children 5,3 β 10β₯5,10β₯3 β. parent(5,index1) has child 4(index3) β 5β₯4 β.)
STEP 2 β Repeatedly extract max (swap root with last element of the CURRENT heap region,
shrink the heap, sift-down the new root):
Heap region size 5: [10,5,3,4,1] β swap root(10) with last(1) β [1,5,3,4,10]
Sorted region (end): [10]. Sift-down 1 within [1,5,3,4] (size 4) β [5,4,3,1]... let's re-derive:
[1,5,3,4] sift down: compare 1 vs children 5,3 β swap with 5 (larger child) β [5,1,3,4]
continue: 1 at index1, children index3=4 β 1<4 swap β [5,4,3,1]
Heap region now: [5,4,3,1], Sorted region: [10]
Heap region size 4: [5,4,3,1] β swap root(5) with last(1) β [1,4,3,5]
Sorted region: [5,10]. Sift-down 1 within [1,4,3] (size 3):
compare 1 vs children 4,3 β swap with 4 β [4,1,3]
Heap region: [4,1,3], Sorted region: [5,10]
Heap region size 3: [4,1,3] β swap root(4) with last(3) β [3,1,4]
Sorted region: [4,5,10]. Sift-down 3 within [3,1] (size 2):
compare 3 vs child 1 β 3>1, no swap needed
Heap region: [3,1], Sorted region: [4,5,10]
Heap region size 2: [3,1] β swap root(3) with last(1) β [1,3]
Sorted region: [3,4,5,10]. Sift-down 1 within [1] (size 1) β nothing to do.
Heap region: [1], Sorted region: [3,4,5,10]
Heap region size 1: trivially sorted, done.
FINAL: [1,3,4,5,10] β
4. Complexity Analysis
Time: O(n log n), guaranteed in all cases.
Building the initial heap is O(n) (the same surprising-but-proven bound from the Data Structures guideβs Heap chapter β bottom-up sift-down, not naive one-by-one insertion). Then there are n extraction steps, each costing O(log n) (one sift-down per extraction, and the heap shrinks by one each time, but sift-downβs cost is still bounded by O(log(current heap size)) = O(log n)). Total: O(n) [build] + O(n log n) [n extractions Γ O(log n) each] = O(n log n).
Why itβs guaranteed, unlike Quick Sort: Heap Sortβs structure β a complete binary tree stored as an array β has height exactly βlogβ nβ by definition, completely independent of the dataβs actual values (unlike Quick Sortβs pivot-dependent, data-dependent partition balance, or even Merge Sortβs need to re-derive the balanced-split argument). Every single sift-down, in every case, costs at most O(log n) β thereβs no βunlucky dataβ scenario that can degrade this.
Space: O(1) extra β genuinely in-place; unlike Quick Sortβs O(log n) recursion stack, Heap Sortβs extraction loop is naturally iterative, needing no recursion at all (sift-down itself is typically implemented iteratively too).
5. Advantages
- Guaranteed O(n log n) in every case, like Merge Sort β no adversarial input can degrade it, unlike Quick Sort.
- O(1) extra space, genuinely in-place β better than both Merge Sort (O(n)) and even Quick Sort (O(log n) stack).
- Combines the best guarantees of both prior algorithms into one β theoretically the βsafestβ general-purpose comparison sort.
6. Limitations
- Not stable β the heap-extraction process has no mechanism to preserve relative order of equal elements.
- Worse real-world constant factors than Quick Sort (and often than Merge Sort) due to poor cache locality β heap operations jump around the array via parent/child index arithmetic (
2i+1,2i+2), which doesnβt access memory sequentially the way Merge Sortβs linear merge or Quick Sortβs linear partition scan does. In practice, Heap Sort is usually the slowest of the three O(n log n) sorts on typical hardware, despite matching or beating them asymptotically. - Less naturally parallelizable than Merge Sort (the heap operations are inherently sequential in a way merge sortβs independent-subarray recursion is not).
7. Real-World Applications
- Systems requiring both a strict worst-case time guarantee AND memory efficiency: embedded/real-time systems where O(n) extra space (Merge Sort) is unacceptable but O(nΒ²) worst-case risk (unmitigated Quick Sort) is also unacceptable.
- Introsort (hybrid sorts): as mentioned in the Quick Sort chapter, C++βs
std::sorttypically falls back to Heap Sort specifically when Quick Sortβs recursion depth suggests a worst-case scenario is unfolding β Heap Sortβs guaranteed bound acts as a safety net without needing Merge Sortβs extra memory. - Priority-based/selection problems more broadly: Heap Sort is really βrepeated extract-maxβ applied to sorting β the same underlying mechanism (Data Structures guide, Ch.5) powers task scheduling, top-K queries, and any other priority-queue-driven application, of which sorting is just one specific use.
- Operating Systems: Some kernel-level sorting tasks with strict worst-case timing requirements.
8. C++ Implementation
#include <iostream>
#include <vector>
// Sift down the element at index i, within a heap region of the given size.
// Identical in spirit to the Data Structures guide's Heap chapter, adapted for in-place array sorting.
void siftDown(std::vector<int>& arr, int size, int i) {
while (true) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < size && arr[left] > arr[largest]) largest = left;
if (right < size && arr[right] > arr[largest]) largest = right;
if (largest == i) break; // heap property restored, stop
std::swap(arr[i], arr[largest]);
i = largest;
}
}
// Heap Sort. O(n log n) guaranteed, O(1) extra space.
void heapSort(std::vector<int>& arr) {
int n = static_cast<int>(arr.size());
// STEP 1: Build a Max-Heap in-place. O(n) β bottom-up from the last non-leaf node.
for (int i = n / 2 - 1; i >= 0; --i) {
siftDown(arr, n, i);
}
// STEP 2: Repeatedly extract the max (root) to the end of the shrinking heap region.
for (int end = n - 1; end > 0; --end) {
std::swap(arr[0], arr[end]); // move current max to its final sorted position
siftDown(arr, end, 0); // restore heap property within the shrunk region [0, end)
}
}
// Example usage
int main() {
std::vector<int> arr = {4, 10, 3, 5, 1};
heapSort(arr);
for (int x : arr) std::cout << x << " ";
std::cout << "\n"; // 1 3 4 5 10
return 0;
}
9. Code Walkthrough
siftDownβssizeparameter: Unlike a standalone heap (Data Structures guide, Ch.5), Heap Sortβs heap shrinks with every extraction βsizerepresents the current boundary of the βstill a heapβ region, distinct from the arrayβs total length. This is the key adaptation that makes the same sift-down logic serve double duty for both build-heap and the extraction loop.- STEP 1βs loop (
i = n/2 - 1down to0): Identical to the Data Structures guideβs O(n) build-heap technique β starting from the last non-leaf node and working backward ensures every subtree is a valid heap by the time its parent is sifted down. - STEP 2βs
swapthensiftDown: Each iteration does exactly two things: (1) move the current maximum (always atarr[0], guaranteed by the heap property) to its final position atarr[end], and (2) restore the heap property for the now-shrunk region[0, end)by sifting the newly-placed root value down. This pair of operations, repeated n-1 times, is the entire sorting mechanism. - Why
end > 0(notend >= 0) in the extraction loop: whenendreaches 0, thereβs exactly one element left (arr[0]), which is trivially already in its correct position β no swap or sift-down is needed.
Common mistakes to watch for here:
- Confusing the shrinking heap
sizewith the arrayβs total length β using the wrong bound causes sift-down to incorrectly consider already-sorted (and no longer part of the heap) elements as heap children. - Forgetting that Heap Sortβs heap is a Max-Heap specifically (to produce ascending sorted output) β a Min-Heap would need extraction into the front of a growing sorted region instead, a less natural in-place adaptation.
- Assuming stability β like Quick Sort, Heap Sortβs swaps can reorder equal elements relative to each other.
10. Dry Run
Already fully traced in section 3, extracting 10, then 5, then 4, then 3, then 1 (in that order, each landing at the correct position from the end backward), producing [1,3,4,5,10].
Complexity bookkeeping across the extraction loop:
| Extraction | Heap size before | Sift-down cost (max levels) |
|---|---|---|
| 1st (extract 10) | 5 | β€ βlogβ5β = 2 |
| 2nd (extract 5) | 4 | β€ βlogβ4β = 2 |
| 3rd (extract 4) | 3 | β€ βlogβ3β = 1 |
| 4th (extract 3) | 2 | β€ βlogβ2β = 1 |
Total sift-down work across all extractions sums to O(n log n) β this table makes concrete exactly what section 4βs complexity argument means in practice.
11. Complexity Table
| Case | Time | Space |
|---|---|---|
| Best | O(n log n) | O(1) |
| Average | O(n log n) | O(1) |
| Worst | O(n log n) | O(1) |
Every entry explained: All three cases coincide because the heapβs shape (a complete binary tree with height exactly βlogβ nβ) is entirely determined by n, never by the dataβs actual values β there is no analogous βbad pivotβ or βbad splitβ scenario that Quick Sort or an unlucky comparison-heavy algorithm could suffer from. Every sift-down, in every case, costs at most O(log(current heap size)).
12. Common Mistakes
- Confusing the shrinking heap size with array length in the extraction loopβs
siftDowncalls. - Using a Min-Heap instead of a Max-Heap for ascending-order output (or forgetting to flip comparisons if adapting for descending order).
- Assuming stability β Heap Sort, like Quick Sort, does not preserve relative order of equal elements.
- Underestimating real-world slowness relative to Quick Sort on typical (non-adversarial) data β Heap Sortβs asymptotic guarantees donβt translate to it being the fastest choice in practice, only the safest.
- Implementing build-heap as repeated single inserts (O(n log n)) instead of the bottom-up O(n) technique β loses a real, well-known optimization.
13. Interview Questions
Conceptual:
- Why does Heap Sort guarantee O(n log n) in every case, unlike Quick Sort?
- Compare Heap Sort, Merge Sort, and Quick Sort across time guarantee, space, stability, and real-world speed β when would you choose each?
- Why is Heap Sort typically slower in practice than Quick Sort despite matching or beating its asymptotic complexity?
- How does Heap Sort reuse the build-heap technique from the Heap data structure chapter?
- Why is Heap Sort not stable, and can it be made stable? (Generally no, not without sacrificing its O(1) space advantage.)
Coding:
- Implement Heap Sort from scratch (build-heap + extraction loop).
- Sort in descending order using a Min-Heap-based Heap Sort.
- Find the K largest elements using a partial Heap Sort (extract only K times, not all n).
- Implement introsort-style hybrid: Quick Sort with a Heap Sort fallback triggered by excessive recursion depth.
Follow-ups / interviewer traps:
- βIf you only need the top K elements, do you need to fully heap-sort the array?β (no β build the heap once, O(n), then extract only K times, O(K log n) β much better than fully sorting when K << n)
- βWhy does introsort fall back to Heap Sort specifically, rather than Merge Sort, when Quick Sortβs recursion gets too deep?β (tests understanding that Heap Sortβs O(1) space fits naturally into an in-place-oriented hybrid, whereas falling back to Merge Sort would reintroduce the O(n) space Quick Sort was chosen to avoid)
14. Practice Problems
Easy
- Kth Largest Element in a Stream (LeetCode 703) β heap-based, related mechanism
Medium
- Sort an Array (LeetCode 912) β implement and benchmark against Merge/Quick Sort
- Kth Largest Element in an Array (LeetCode 215) β compare a partial-heap-sort approach against Quickselect (Chapter 4)
- Top K Frequent Elements (LeetCode 347)
Hard
- Find Median from Data Stream (LeetCode 295) β two-heap technique, conceptually related
Also recommended: benchmark Heap Sort against Merge Sort and Quick Sort on the same random, sorted, and reverse-sorted inputs β directly observe that all three achieve similar asymptotic behavior on random data, but with meaningfully different wall-clock times due to cache locality differences.
15. Summary
Key takeaways:
- Heap Sort combines Merge Sortβs guaranteed O(n log n) with Quick Sortβs in-place (here, even better β O(1) vs O(log n)) space usage, at the cost of stability and real-world speed (poor cache locality).
- Itβs built entirely from the Heap data structureβs existing machinery (build-heap in O(n), sift-down in O(log n)) β nothing new to learn mechanically, just a new application of a structure you already know.
- In practice, itβs the βsafety netβ choice β theoretically excellent guarantees, but usually not the fastest option on typical, non-adversarial data.
Complexity recap:
| Time (all cases) | Space | Stable | |
|---|---|---|---|
| Heap Sort | O(n log n) | O(1) | No |
Decision guide: Choose Heap Sort when you need both a guaranteed worst-case time bound AND strict memory constraints (ruling out Merge Sortβs O(n) space) β otherwise, Quick Sort (with randomization) usually wins on real-world speed, and Merge Sort wins when stability is required. Heap Sortβs most common real-world role is as the safety-net fallback within hybrid sorts like introsort, rather than as a standalone first choice.
Next chapter: 06_non_comparison_sorts.md β Counting Sort, Radix Sort, Bucket Sort.
Chapter 6: Non-Comparison Sorts (Counting, Radix, Bucket)
Study time: ~5-6 hours | Prerequisite: Arrays, basic understanding of comparison sorts (Ch. 2-5) | Difficulty: Intermediate
1. Introduction
Definition: Counting Sort, Radix Sort, and Bucket Sort are sorting algorithms that never compare two elements to each other β instead, they exploit structural knowledge about the data (small integer range, fixed number of digits, known distribution) to place elements directly into their correct positions.
Purpose: To sort in O(n + k) time (where k relates to the dataβs range or digit count) β genuinely faster than the O(n log n) lower bound that applies to any comparison-based sort, by sidestepping comparisons entirely.
Problem solved: Sorting integers (or integer-like keys) drawn from a bounded or structured range, where that structure can be exploited for better-than-comparison-sort performance.
2. Intuition
Comparison sorts (Chapters 2-5) are provably bounded below by Ξ©(n log n) β this isnβt a limitation of any particular algorithm, itβs a mathematical fact about any algorithm that only learns information by comparing pairs of elements (there are n! possible orderings, and each comparison yields at most 1 bit of information, so you need at least logβ(n!) β n log n comparisons in the worst case β the same information-theoretic argument used for Binary Searchβs optimality in Chapter 1).
Non-comparison sorts escape this bound by not comparing at all. Instead:
- Counting Sort: if you know values range from 0 to k, count how many times each value occurs, then directly compute where each value belongs in the output β like sorting exam scores (0-100) by literally counting how many students got each score, then listing them in order.
- Radix Sort: sort numbers digit by digit (least significant to most significant), using a stable sort (typically Counting Sort) at each digit position β like sorting a stack of punch cards column by column, a technique literally used by mechanical card-sorting machines in the pre-computer era.
- Bucket Sort: distribute elements into several βbucketsβ based on value ranges, sort each bucket individually (with any algorithm, often insertion sort since buckets are small), then concatenate β like presorting mail by zip code region before finer sorting within each region.
3. Step-by-Step Working
(a) Counting Sort β array [4, 2, 2, 8, 3, 3, 1], range 0-8
STEP 1: Count occurrences of each value (0 to 8):
Value: 0 1 2 3 4 5 6 7 8
Count: 0 1 2 2 1 0 0 0 1
STEP 2: Convert counts to PREFIX sums (cumulative count) β this gives the
position where each value's LAST occurrence should go in the output:
Value: 0 1 2 3 4 5 6 7 8
Cumul: 0 1 3 5 6 6 6 6 7
STEP 3: Build the output by placing each input element at its cumulative-count
position, then DECREMENTING that count (to place duplicates correctly,
and to preserve stability by processing the input right-to-left):
Process input right-to-left: 1, 3, 3, 8, 2, 2, 4
'1' β cumul[1]=1 β place at output index 0, decrement cumul[1] to 0
'3' β cumul[3]=5 β place at output index 4, decrement cumul[3] to 4
'3' β cumul[3]=4 β place at output index 3, decrement cumul[3] to 3
'8' β cumul[8]=7 β place at output index 6, decrement cumul[8] to 6
'2' β cumul[2]=3 β place at output index 2, decrement cumul[2] to 2
'2' β cumul[2]=2 β place at output index 1, decrement cumul[2] to 1
'4' β cumul[4]=6 β place at output index 5, decrement cumul[4] to 5
Output: [1, 2, 2, 3, 3, 4, 8] β
(b) Radix Sort β array [170, 45, 75, 90, 802, 24, 2, 66]
Sort by ONES digit first (using Counting Sort, stable):
[170, 90, 802, 2, 24, 45, 75, 66]
(0) (0) (2) (2) (4) (5) (5) (6)
Sort by TENS digit next:
[802, 2, 24, 45, 66, 170, 75, 90]
(0) (0) (2) (4) (6) (7) (7) (9)
Sort by HUNDREDS digit last:
[2, 24, 45, 66, 75, 90, 170, 802]
(0) (0) (0) (0) (0) (0) (1) (8)
Final: [2, 24, 45, 66, 75, 90, 170, 802] β fully sorted after 3 digit-passes
Why sorting least-significant-digit first works: because each digit pass uses a stable sort, elements that tie on the current digit retain their relative order from the previous pass β which was already correctly sorted on less significant digits. This stacking of stable sorts, digit by digit from least to most significant, is what makes the final result fully correct.
(c) Bucket Sort β array of floats [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12] (uniformly distributed in [0,1))
Create 8 buckets, each covering a 1/8 range: [0,.125), [.125,.25), ... [.875,1)
Distribute:
Bucket 0 [0,.125): 0.12
Bucket 1 [.125,.25): 0.17, 0.21
Bucket 2 [.25,.375): 0.26
Bucket 3 [.375,.5): 0.39
Bucket 4 [.5,.625): (empty)
Bucket 5 [.625,.75): 0.72
Bucket 6 [.75,.875): 0.78
Bucket 7 [.875,1): 0.94
Sort each bucket individually (insertion sort β buckets are small):
Bucket 1: [0.17, 0.21] (already sorted after insertion sort)
Concatenate all buckets in order:
[0.12, 0.17, 0.21, 0.26, 0.39, 0.72, 0.78, 0.94] β
4. Complexity Analysis
Counting Sort: O(n + k) where k is the value range. Building the count array is O(k); the cumulative sum pass is O(k); placing every input element is O(n). Total: O(n + k) β genuinely linear when k = O(n), but degrades badly when k >> n (e.g., sorting 10 values that range from 0 to 10,000,000 wastes enormous time/space on mostly-empty counting buckets).
Radix Sort: O(d Β· (n + k)) where d is the number of digits and k is the base (typically k=10 for base-10 digits, or k=256 for byte-wise radix on binary data). Each of the d digit-passes runs a full O(n+k) Counting Sort. For fixed-width integers (e.g., 32-bit integers, d is bounded by a small constant like 10 decimal digits or 4 bytes), this is effectively O(n) β linear β which is asymptotically better than any comparison sortβs O(n log n) lower bound, precisely because Radix Sort never compares elements directly.
Bucket Sort: O(n + k) average case, assuming roughly uniform input distribution across k buckets β each bucket ends up with about n/k elements, and sorting each small bucket (e.g., with insertion sort) costs O((n/k)Β²) per bucket, times k buckets, giving O(nΒ²/k) total for the bucket-sorting step; choosing k β n makes this O(n) average. Worst case O(nΒ²) if the distribution is highly skewed (e.g., all elements land in one bucket, degenerating to sorting the whole array with insertion sort).
Why these can beat the O(n log n) comparison-sort lower bound: that lower bound applies specifically to algorithms that only extract information via pairwise comparisons. Counting Sort, Radix Sort, and (average-case) Bucket Sort extract information a fundamentally different way β direct indexing/counting based on value β which isnβt subject to the same information-theoretic constraint at all.
5. Advantages
- Genuinely faster than O(n log n) when their structural assumptions hold (bounded range for Counting Sort, fixed digit-width for Radix Sort, roughly uniform distribution for Bucket Sort).
- Counting Sort and Radix Sort (with a stable underlying sort) are stable β useful for multi-key sorting (e.g., sort by one field, then stably re-sort by another).
- Radix Sort scales to arbitrarily large numbers (or fixed-width strings) with cost proportional to digit/character count, not value magnitude.
6. Limitations
- Only applicable to specific data types β integers, or data that can be mapped to integers/digits (not general comparable objects with an arbitrary
<operator). - Counting Sortβs O(k) space/time can be disastrous if the value range is large relative to n (e.g., sorting 100 numbers where one happens to be a billion wastes a billion-sized count array).
- Bucket Sortβs average-case guarantee assumes roughly uniform distribution β skewed real-world data (e.g., many exact duplicates, or a heavily clustered distribution) can degrade it toward O(nΒ²).
- Radix Sortβs constant factor (d passes, each a full linear scan) can make it slower in practice than a well-tuned Quick Sort for moderate n, even when asymptotically comparable or better.
7. Real-World Applications
- Counting Sort: grading systems (bounded score ranges), histogram-based image processing (pixel intensity values are a small bounded range, 0-255), radix sortβs own internal digit-counting step.
- Radix Sort: sorting large datasets of fixed-width keys β IP addresses, phone numbers, employee/student ID numbers, fixed-length strings. Historically used literally in mechanical punch-card sorting machines (the origin of the βradixβ β meaning βbaseβ or βrootβ β naming).
- Bucket Sort: sorting data known to be roughly uniformly distributed β hash-table-adjacent bucketing schemes, certain graphics/rendering pipeline sorting tasks (e.g., sorting objects by a continuous depth/coordinate value).
- Databases: some specialized bulk-loading/bucketing strategies for building indexes over known-range key sets.
- Networking: sorting/grouping packets by fixed-width header fields (e.g., port numbers) can use radix-sort-like techniques.
- Compilers: bucket-based symbol categorization in some optimization passes.
8. C++ Implementation
#include <iostream>
#include <vector>
#include <algorithm>
// Counting Sort. O(n + k), stable. Assumes non-negative integers with known max value.
std::vector<int> countingSort(const std::vector<int>& arr) {
if (arr.empty()) return arr;
int maxVal = *std::max_element(arr.begin(), arr.end());
std::vector<int> count(maxVal + 1, 0);
for (int x : arr) count[x]++; // STEP 1: count occurrences
for (int i = 1; i <= maxVal; ++i) count[i] += count[i - 1]; // STEP 2: cumulative sum
std::vector<int> output(arr.size());
for (int i = static_cast<int>(arr.size()) - 1; i >= 0; --i) { // STEP 3: place right-to-left for stability
output[--count[arr[i]]] = arr[i];
}
return output;
}
// One digit-pass of Counting Sort, used internally by Radix Sort. Sorts by the
// digit at the given place value (1, 10, 100, ...). Stable.
void countingSortByDigit(std::vector<int>& arr, int placeValue) {
int n = static_cast<int>(arr.size());
std::vector<int> output(n);
std::vector<int> count(10, 0); // digits are always 0-9
for (int x : arr) count[(x / placeValue) % 10]++;
for (int i = 1; i < 10; ++i) count[i] += count[i - 1];
for (int i = n - 1; i >= 0; --i) {
int digit = (arr[i] / placeValue) % 10;
output[--count[digit]] = arr[i];
}
arr = output;
}
// Radix Sort. O(d * (n + k)), effectively O(n) for fixed-width integers.
void radixSort(std::vector<int>& arr) {
if (arr.empty()) return;
int maxVal = *std::max_element(arr.begin(), arr.end());
for (int placeValue = 1; maxVal / placeValue > 0; placeValue *= 10) {
countingSortByDigit(arr, placeValue); // one stable pass per digit, least significant first
}
}
// Bucket Sort. O(n + k) average case for roughly uniform data in [0, 1).
std::vector<double> bucketSort(std::vector<double>& arr) {
int n = static_cast<int>(arr.size());
std::vector<std::vector<double>> buckets(n);
for (double x : arr) {
int bucketIndex = static_cast<int>(x * n); // map [0,1) value to a bucket index
if (bucketIndex == n) bucketIndex = n - 1; // guard against x exactly == 1.0
buckets[bucketIndex].push_back(x);
}
for (auto& bucket : buckets) {
std::sort(bucket.begin(), bucket.end()); // sort each (small) bucket individually
}
std::vector<double> result;
result.reserve(n);
for (auto& bucket : buckets) {
for (double x : bucket) result.push_back(x); // concatenate buckets in order
}
return result;
}
// Example usage
int main() {
std::vector<int> a = {4, 2, 2, 8, 3, 3, 1};
auto sortedA = countingSort(a);
std::cout << "Counting Sort: ";
for (int x : sortedA) std::cout << x << " ";
std::cout << "\n"; // 1 2 2 3 3 4 8
std::vector<int> b = {170, 45, 75, 90, 802, 24, 2, 66};
radixSort(b);
std::cout << "Radix Sort: ";
for (int x : b) std::cout << x << " ";
std::cout << "\n"; // 2 24 45 66 75 90 170 802
std::vector<double> c = {0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12};
auto sortedC = bucketSort(c);
std::cout << "Bucket Sort: ";
for (double x : sortedC) std::cout << x << " ";
std::cout << "\n"; // 0.12 0.17 0.21 0.26 0.39 0.72 0.78 0.94
return 0;
}
9. Code Walkthrough
countingSortβs cumulative-sum step: After this step,count[v]no longer means βhow many times v occursβ β it now means βhow many elements are β€ v,β which is exactly the final output index (one past the last occurrence) that value vβs elements should occupy.- Processing the input right-to-left in the placement step: This specific detail is what makes Counting Sort stable β processing left-to-right would still produce a correctly sorted output, but equal elements would end up in reversed relative order; going right-to-left preserves their original relative order instead.
countingSortByDigitβs(x / placeValue) % 10: This extracts a single decimal digit at the given place value β e.g., forplaceValue=100,(802/100)%10 = 8, correctly extracting the hundreds digit. This function is literally the same Counting Sort algorithm, just keyed on one digit instead of the whole value.radixSortβs loop conditionmaxVal / placeValue > 0: This naturally stops onceplaceValueexceeds the largest numberβs digit count β no need to precompute the exact number of digits separately.bucketSortβsx * nbucket mapping: For data uniformly distributed in [0,1), multiplying bynand truncating maps each value to one ofnbuckets roughly evenly β this is the specific assumption that gives Bucket Sort its average-case O(n) behavior; a non-uniform distribution would need a different (often more complex) mapping function to stay balanced.
Common mistakes to watch for here:
- Processing Counting Sortβs placement step left-to-right instead of right-to-left, silently breaking stability.
- Forgetting to reset/rebuild the count array between Radix Sortβs digit passes (each
countingSortByDigitcall needs its own fresh count array, which the implementation above handles correctly by declaring it locally each call). - Using Bucket Sort on non-uniformly-distributed data without adjusting the bucket-mapping strategy, silently degrading toward O(nΒ²).
- Using Counting Sort on data with a huge value range relative to n, wasting enormous time/space unnecessarily.
10. Dry Run
Radix Sort on [170, 45, 75, 90, 802, 24, 2, 66], ones-digit pass:
| Value | Ones digit | count[] before cumsum | count[] after cumsum |
|---|---|---|---|
| 170 | 0 | count[0]=2 (170,90) | β |
| 45 | 5 | count[5]=2 (45,75) | β |
| 75 | 5 | (see above) | β |
| 90 | 0 | (see above) | β |
| 802 | 2 | count[2]=1 | β |
| 24 | 4 | count[4]=1 | β |
| 2 | 2 | count[2]=1 (tied with 802βs digit 2 β but 2βs actual value differs, only digit matters here) | β |
| 66 | 6 | count[6]=1 | β |
Full counting-and-placement process (right-to-left over input, as in section 9) produces [170, 90, 802, 2, 24, 45, 75, 66] β matching section 3βs trace exactly. β
11. Complexity Table
| Algorithm | Best | Average | Worst | Space | Stable? |
|---|---|---|---|---|---|
| Counting Sort | O(n+k) | O(n+k) | O(n+k) | O(n+k) | Yes |
| Radix Sort | O(d(n+k)) | O(d(n+k)) | O(d(n+k)) | O(n+k) | Yes |
| Bucket Sort | O(n+k) | O(n+k) | O(nΒ²) | O(n+k) | Depends on per-bucket sort choice |
Every entry explained: Counting Sort and Radix Sort have no data-dependent variation in their complexity β every case is identical, because the algorithmβs work is entirely determined by n, k (and d), never by the actual arrangement of values (unlike comparison sorts, which can have best/worst-case gaps based on how βclose to sortedβ the input already is). Bucket Sortβs worst case O(nΒ²) arises specifically when the distribution assumption fails and all elements cluster into one bucket, degenerating to sorting that entire cluster with whatever algorithm sorts each bucket (commonly insertion sort, hence O(nΒ²)).
12. Common Mistakes
- Using Counting Sort when the value range k is much larger than n β wastes enormous time and space; always check this ratio before choosing Counting Sort.
- Breaking stability by processing Counting Sortβs placement step in the wrong order.
- Applying Bucket Sort to skewed/clustered data without adjusting the bucketing strategy, silently degrading toward O(nΒ²).
- Forgetting Radix Sort requires non-negative integers in its basic form β negative numbers need a modified approach (e.g., offsetting all values, or handling the sign bit separately).
- Assuming these algorithms work for general comparable objects β they fundamentally require integer (or integer-mappable) keys, unlike comparison sorts which work for anything with a defined
<operator.
13. Interview Questions
Conceptual:
- Why can Counting Sort and Radix Sort beat the O(n log n) comparison-sort lower bound? What does that lower bound actually apply to?
- Explain why Radix Sort must process digits from least-significant to most-significant, and why the per-digit sort must be stable.
- When would Counting Sort be a poor choice despite the data being integers?
- What assumption does Bucket Sortβs average-case analysis depend on, and what happens when that assumption fails?
- Compare Radix Sortβs O(d(n+k)) to a comparison sortβs O(n log n) β under what conditions is Radix Sort actually faster in practice?
Coding:
- Implement Counting Sort, Radix Sort, and Bucket Sort from scratch.
- Sort an array of strings by length using Counting Sort (bounded length range).
- Sort negative and positive integers together using Radix Sort (requires handling the sign).
- Given an array of ages (0-120), sort it in O(n) using Counting Sort.
- Maximum Gap (LeetCode 164) β classic Bucket-Sort-adjacent application (find max gap between sorted elements in O(n)).
Follow-ups / interviewer traps:
- βYour data has values up to 10^9 but only 100 elements β is Counting Sort still a good choice?β (no β k >> n makes it far worse than a comparison sort here; tests recognizing the applicability boundary)
- βCan Radix Sort sort strings, not just integers?β (yes β treat characters as digits in a larger base, e.g., base 256 for bytes; tests generalizing beyond the numeric example)
- βHow would you sort negative numbers with Radix Sort?β (tests awareness that the basic algorithm assumes non-negative integers, and a real fix β e.g., offsetting or separating negative/positive partitions β is needed)
14. Practice Problems
Easy
- Sort an Array (LeetCode 912) β try a non-comparison approach when the value range is known/bounded
- Height Checker (LeetCode 1051) β natural Counting Sort application
Medium
- Sort Colors (LeetCode 75) β a 3-value special case, effectively a tiny Counting Sort
- Relative Sort Array (LeetCode 1122) β Counting-Sort-based
- Maximum Gap (LeetCode 164) β Bucket Sort application
Hard
- Sort an array of large fixed-width numbers efficiently using Radix Sort as a benchmark against
std::sort
Also recommended: benchmark Counting/Radix/Bucket Sort against Quick Sort/std::sort on data specifically suited to each (small-range integers, fixed-width numbers, uniformly distributed floats) β observe the real speedup non-comparison sorts provide under their ideal conditions.
15. Summary
Key takeaways:
- Non-comparison sorts escape the O(n log n) comparison-sort lower bound by extracting information a fundamentally different way β direct counting/indexing rather than pairwise comparison.
- Counting Sort needs a small value range (k = O(n)); Radix Sort extends this to larger values by sorting digit-by-digit; Bucket Sort needs (roughly) uniformly distributed data.
- All three can be made stable, which matters for their common role as building blocks (Radix Sort literally is repeated stable Counting Sort).
- These are specialized tools β powerful when their structural assumptions hold, but inapplicable or actively worse than comparison sorts when they donβt.
Complexity recap:
| Time | Space | Requires | |
|---|---|---|---|
| Counting Sort | O(n+k) | O(n+k) | Small integer range |
| Radix Sort | O(d(n+k)) | O(n+k) | Fixed-width integers/strings |
| Bucket Sort | O(n+k) avg | O(n+k) | Roughly uniform distribution |
Decision guide: Reach for Counting Sort when sorting integers with a small, known range. Reach for Radix Sort when sorting larger fixed-width integers or strings where digit-by-digit processing is natural. Reach for Bucket Sort when data is known (or can be verified) to be roughly uniformly distributed over a range. When none of these structural assumptions clearly hold, default back to a comparison sort (Quick Sort/Merge Sort/your languageβs built-in sort) β forcing a non-comparison sort onto unsuitable data can easily perform worse than the comparison-sort alternative.
Next chapter: 07_two_pointer.md
Chapter 7: Two Pointer
Study time: ~4-5 hours | Prerequisite: Arrays, Sorting (Ch. 2-4) | Difficulty: Beginner-Intermediate
1. Introduction
Definition: The Two Pointer technique uses two index variables (βpointersβ) that traverse an array (or string) β either moving toward each other from opposite ends, moving in the same direction at different speeds, or one fast/one slow β to solve problems in O(n) that would otherwise need O(nΒ²) with nested loops.
Purpose: To eliminate a redundant nested loop by exploiting structure (usually sortedness, or a specific traversal pattern) that lets both pointers move monotonically β each pointer only ever advances, never backtracks β guaranteeing the total work stays linear.
Problem solved: A huge class of βfind a pair/subarray/structural propertyβ problems that a naive nested-loop approach solves in O(nΒ²), but which secretly only need O(n) once you recognize the right pointer-movement pattern.
2. Intuition
Opposite Direction (the classic βsorted array, find a pairβ pattern): if an array is sorted and youβre looking for two elements summing to a target, starting one pointer at each end lets you reason: βif the current sum is too small, the only way to increase it is to move the left pointer right (since the array is sorted, any leftward move on the right pointer can only decrease or keep the sum). If the current sum is too large, move the right pointer left.β This eliminates the need to check every pair β each comparison rules out an entire row or column of the conceptual nΓn pair-grid at once.
Same Direction (the βpartition/filter in-placeβ pattern): one pointer tracks βwhere the next valid element should go,β another scans forward looking for valid elements β this is exactly how youβd sort mail into βkeepβ and βdiscardβ piles while only walking through the stack once, physically moving items as you find them rather than making two separate passes.
Fast & Slow (Floydβs Tortoise and Hare): two pointers move through a sequence at different speeds (typically 1 step vs. 2 steps) β if thereβs a cycle, the fast pointer will eventually βlapβ the slow one and theyβll meet; if thereβs no cycle, the fast pointer simply reaches the end first. This is the same technique introduced for linked list cycle detection in the Data Structures guide, generalized here as a standalone pattern.
3. Step-by-Step Working
(a) Opposite Direction β find a pair summing to 13 in sorted [1, 3, 5, 7, 9, 11]
left=0(1), right=5(11). Sum=1+11=12 < 13 β too small β move LEFT pointer right.
left=1(3), right=5(11). Sum=3+11=14 > 13 β too large β move RIGHT pointer left.
left=1(3), right=4(9). Sum=3+9=12 < 13 β too small β move LEFT pointer right.
left=2(5), right=4(9). Sum=5+9=14 > 13 β too large β move RIGHT pointer left.
left=2(5), right=3(7). Sum=5+7=12 < 13 β too small β move LEFT pointer right.
left=3(7), right=3(7). Pointers meet β no pair found within these bounds.
(If instead target were 12: the very first check would have found 1+11=12 β MATCH immediately.)
Each step eliminates exactly one row or column from consideration β n pointer moves total, giving O(n) instead of checking all O(nΒ²) pairs.
(b) Same Direction β remove duplicates in-place from sorted [1, 1, 2, 2, 2, 3, 4, 4]
slow=0 (points to the last confirmed-unique element written so far)
fast scans forward:
fast=1: arr[1]=1 == arr[slow]=1 β duplicate, skip (don't advance slow)
fast=2: arr[2]=2 != arr[slow]=1 β new unique value β slow=1, arr[slow]=2 β [1,2,2,2,2,3,4,4]
fast=3: arr[3]=2 == arr[slow]=2 β duplicate, skip
fast=4: arr[4]=2 == arr[slow]=2 β duplicate, skip
fast=5: arr[5]=3 != arr[slow]=2 β new unique β slow=2, arr[slow]=3 β [1,2,3,2,2,3,4,4]
fast=6: arr[6]=4 != arr[slow]=3 β new unique β slow=3, arr[slow]=4 β [1,2,3,4,2,3,4,4]
fast=7: arr[7]=4 == arr[slow]=4 β duplicate, skip
Final unique portion: arr[0..slow] = [1,2,3,4] (everything after slow is now irrelevant leftover data)
(c) Fast & Slow β detect a cycle in a sequence (conceptually, matching the Data Structures guideβs linked-list treatment)
slow moves 1 step at a time, fast moves 2 steps at a time.
If there's a cycle, fast will eventually "lap" slow and they'll occupy the same position β
mathematically guaranteed because the GAP between them shrinks by exactly 1 each step
once both are inside the cycle, so it must eventually reach 0.
If there's no cycle, fast simply reaches the end (a null/boundary) first.
4. Complexity Analysis
Time: O(n) for all three variants, in contrast to the O(nΒ²) a naive nested-loop approach would require for the same problems.
Why Opposite Direction is O(n), not O(nΒ²): each of the n total pointer moves (left advancing or right retreating) permanently shrinks the search space by one β the two pointers can move toward each other at most n times combined before meeting, so the total work across the entire algorithm is bounded by n, not nΒ².
Why Same Direction is O(n): the fast pointer makes exactly n moves (one full pass), and the slow pointer makes at most n moves (never more than fast) β both bounded by a single linear pass, with no nested iteration.
Why Fast & Slow is O(n): even though the fast pointer moves twice as fast, it still only traverses a bounded-length structure a constant number of times before either finding the cycle or reaching the end β the total work remains linear in the structureβs size.
Space: O(1) for all three β this is the other headline advantage: no auxiliary data structure needed, unlike, say, a hash-set-based approach to the same βfind a pairβ problem (which would also be O(n) time, but O(n) space instead of O(1)).
5. Advantages
- Converts many O(nΒ²) nested-loop problems into O(n) β often the single highest-leverage optimization pattern in coding interviews.
- O(1) extra space β genuinely in-place, no auxiliary hash sets or arrays needed (an advantage over equivalent hash-based approaches to the same problems).
- Conceptually simple once the pattern is recognized β the hard part is recognizing when it applies, not implementing it.
6. Limitations
- Opposite Direction typically requires sorted data β if the array isnβt sorted and canβt be cheaply sorted (or sorting would destroy needed information, like original indices), this variant doesnβt directly apply.
- Doesnβt generalize to problems needing information about all pairs simultaneously (e.g., counting every pair satisfying a condition, rather than just finding one or partitioning) β some counting variants exist but require more care.
- Recognizing which variant (opposite/same/fast-slow) applies to a novel problem is a genuine pattern-recognition skill that takes deliberate practice to build.
7. Real-World Applications
- Databases: merge-join operations (combining two sorted result sets) use an opposite-direction-style two-pointer merge.
- Text Processing: palindrome checking, string reversal in-place β natural opposite-direction applications.
- Memory Management: in-place array compaction/garbage collection (moving βliveβ objects to the front, analogous to the same-direction duplicate-removal pattern).
- Networking: TCP congestion controlβs sliding window (closely related to the Sliding Window pattern, next chapter) tracks a moving range of βin-flightβ packets using pointer-like bounds.
- Version Control: diff algorithms use two-pointer-style techniques to find common/differing regions between two sequences.
- Operating Systems: cycle detection in resource-allocation graphs (deadlock detection) uses fast-slow-pointer-style techniques conceptually related to Floydβs algorithm.
8. C++ Implementation
#include <iostream>
#include <vector>
#include <algorithm>
// Opposite Direction: find if any pair in a SORTED array sums to target. O(n).
bool twoSumSorted(const std::vector<int>& arr, int target) {
int left = 0, right = static_cast<int>(arr.size()) - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) {
return true; // found a matching pair
} else if (sum < target) {
left++; // sum too small β only increasing left can help (array is sorted)
} else {
right--; // sum too large β only decreasing right can help
}
}
return false;
}
// Same Direction: remove duplicates in-place from a SORTED array, return new length. O(n).
int removeDuplicates(std::vector<int>& arr) {
if (arr.empty()) return 0;
int slow = 0; // slow tracks the last position of a confirmed-unique element
for (int fast = 1; fast < static_cast<int>(arr.size()); ++fast) {
if (arr[fast] != arr[slow]) {
slow++;
arr[slow] = arr[fast]; // write the new unique value into place
}
// if arr[fast] == arr[slow], it's a duplicate β fast advances, slow stays put
}
return slow + 1; // number of unique elements
}
// Fast & Slow: detect whether a sequence (modeled here as a "next" function) has a cycle.
// In a real linked list this would use Node* pointers β see Data Structures guide, Ch.3.
bool hasCycle(const std::vector<int>& next, int start) {
int slow = start, fast = start;
while (next[fast] != -1 && next[next[fast]] != -1) { // -1 represents "end of sequence"
slow = next[slow]; // move 1 step
fast = next[next[fast]]; // move 2 steps
if (slow == fast) return true; // they met β a cycle exists
}
return false; // fast reached the end without meeting slow β no cycle
}
// Example usage
int main() {
std::vector<int> sorted = {1, 3, 5, 7, 9, 11};
std::cout << "twoSumSorted(target=12): " << twoSumSorted(sorted, 12) << "\n"; // 1 (true)
std::cout << "twoSumSorted(target=13): " << twoSumSorted(sorted, 13) << "\n"; // 0 (false)
std::vector<int> withDupes = {1, 1, 2, 2, 2, 3, 4, 4};
int newLen = removeDuplicates(withDupes);
std::cout << "After removeDuplicates, unique portion: ";
for (int i = 0; i < newLen; ++i) std::cout << withDupes[i] << " ";
std::cout << "\n"; // 1 2 3 4
return 0;
}
9. Code Walkthrough
twoSumSortedβs directional logic: The crucial insight encoded insum < target β left++andsum > target β right--is that, because the array is sorted, moving the other pointer in either case could never help β e.g., if the sum is too small, decreasingrightwould only make it smaller still (worse), soleftis the only pointer that can productively move. This is the exact reasoning that makes the algorithm correct, not just fast.removeDuplicatesβs slow/fast roles:slowalways points at the last position that holds a confirmed-final unique value;fastscans ahead looking for the next unique value. The writearr[slow] = arr[fast]only happens when a genuinely new value is found β this is what keeps the βunique so farβ region at the front of the array compact, with no gaps.hasCycleβs loop condition: Checking bothnext[fast] != -1ANDnext[next[fast]] != -1before advancing ensures the fast pointer never tries to take two steps past the actual end of a non-cyclic sequence (which would be an invalid/out-of-bounds access) β this guard is what makes the fast-pointerβs βmove 2 stepsβ safe.- Why
fastmoving 2x speed guarantees meetingslowinside a cycle: once both pointers are inside the cycle, the gap between them (measured along the cycle) decreases by exactly 1 every step (since fast gains 1 net step on slow per iteration) β a gap that shrinks by 1 each step, starting from some finite value, must eventually hit 0, guaranteeing a meeting.
Common mistakes to watch for here:
- Applying
twoSumSortedβs opposite-direction logic to an unsorted array β this technique fundamentally depends on sortedness to guarantee correctness of the pointer-movement decisions. - In
removeDuplicates, forgetting to advanceslowbefore writing, or writing on every iteration instead of only when a new unique value is found. - Off-by-one errors in the fast-pointerβs bounds-checking for cycle detection, risking out-of-bounds access on non-cyclic sequences.
10. Dry Run
Both (a) and (b) from section 3 are already complete, step-by-step dry runs. The key complexity insight worth re-emphasizing from run (a): across the entire twoSumSorted execution on [1,3,5,7,9,11] searching for 13, there were exactly 5 pointer-movement steps before the pointers met β compare this to a brute-force nested loop, which would check up to 6Γ5/2 = 15 pairs for the same 6-element array. The two-pointer techniqueβs advantage becomes dramatically larger as n grows, since itβs O(n) vs. O(nΒ²).
11. Complexity Table
| Variant | Time | Space | Precondition |
|---|---|---|---|
| Opposite Direction | O(n) | O(1) | Sorted data (or a similarly monotonic structure) |
| Same Direction | O(n) | O(1) | Usually sorted (for dedup-style problems), though some same-direction problems work unsorted (e.g., partitioning) |
| Fast & Slow | O(n) | O(1) | A traversable sequence with a well-defined βnextβ step |
Every entry explained: All three variants achieve O(n) because each pointerβs total movement across the entire algorithmβs execution is bounded by the structureβs size (n), never revisiting the same position twice in a way that would reintroduce quadratic behavior β this is the single unifying reason all Two Pointer variants are linear.
12. Common Mistakes
- Using opposite-direction two-pointer on unsorted data β the directional logic (
sum too small β move left) is only valid because of sortedness; applying it blindly to unsorted data gives wrong answers. - Off-by-one errors in loop conditions (
left < rightvsleft <= right) β get this wrong and youβll either miss valid pairs or double-count/incorrectly compare an element against itself. - Forgetting to advance the correct pointer β a common slip is advancing both pointers on every iteration regardless of the comparison outcome, which breaks the techniqueβs correctness guarantee entirely.
- Confusing same-direction (dedup/partition) with opposite-direction (pair-finding) logic β these are genuinely different patterns solving different problem shapes; misapplying one where the other is needed is a common early-learner mistake.
13. Interview Questions
Conceptual:
- Why does opposite-direction two-pointer require sorted data, and what specifically breaks without it?
- Explain why Two Pointer techniques are O(n) rather than O(nΒ²) β whatβs the core argument?
- Compare Two Pointer to a hash-set-based approach for the βfind a pair summing to targetβ problem β whatβs the trade-off?
- How does Fast & Slow pointer relate to the linked-list cycle detection covered in the Data Structures guide?
- Give an example of a problem where Two Pointer does NOT apply, and explain why.
Coding:
- Two Sum II - Input Array Is Sorted (LeetCode 167).
- Remove Duplicates from Sorted Array (LeetCode 26).
- Container With Most Water (LeetCode 11) β opposite-direction with a non-obvious movement rule.
- 3Sum (LeetCode 15) β combines sorting + fixed element + opposite-direction two-pointer.
- Linked List Cycle II β find the cycleβs starting node (fast-slow pointer, with a clever second phase).
- Sort Colors (LeetCode 75) β same-direction, three-way partition variant.
Follow-ups / interviewer traps:
- βCan you solve Two Sum with Two Pointer if the array isnβt sorted?β (only after sorting it first, O(n log n) β but this loses original indices unless you track them separately, a common follow-up trap)
- β3Sum β why do you skip duplicate values while iterating the fixed element?β (tests understanding of avoiding duplicate triplets in the output, a subtle but essential detail)
- βContainer With Most Water β why is it always correct to move the pointer at the SHORTER wall?β (tests a genuine proof-based understanding, not just pattern memorization β moving the taller wallβs pointer can never improve the area, since the shorter wall was already the binding constraint)
14. Practice Problems
Easy
- Two Sum II - Input Array Is Sorted (LeetCode 167)
- Remove Duplicates from Sorted Array (LeetCode 26)
- Valid Palindrome (LeetCode 125)
- Reverse String (LeetCode 344)
Medium
- 3Sum (LeetCode 15)
- Container With Most Water (LeetCode 11)
- Sort Colors (LeetCode 75)
- Linked List Cycle II (LeetCode 142)
Hard
- Trapping Rain Water (LeetCode 42) β two-pointer variant exists alongside the prefix-sum approach
- 4Sum (LeetCode 18)
Also recommended: GeeksforGeeks βTwo Pointer Techniqueβ practice set, Codeforces problems tagged two pointers.
15. Summary
Key takeaways:
- Two Pointer converts O(nΒ²) nested-loop problems into O(n) by ensuring each pointer only ever moves forward (or the two pointers only ever move toward each other), bounding total work by n rather than nΒ².
- Opposite Direction needs sorted (monotonic) data; Same Direction handles partition/dedup-style problems; Fast & Slow detects cycles or finds midpoints.
- The hard skill is pattern recognition β spotting that a problem fits one of these three shapes β not the implementation itself, which is usually just a handful of lines once the right variant is identified.
Complexity recap:
| Time | Space | |
|---|---|---|
| Any Two Pointer variant | O(n) | O(1) |
Decision guide: Reach for Two Pointer whenever a problem involves finding a pair/triple in sorted data, partitioning/deduplicating an array in-place, or detecting a cycle/finding a midpoint in a sequence. If the data isnβt sorted and sorting would destroy needed information (like original indices), consider a hash-based approach instead β same O(n) time, but O(n) space rather than Two Pointerβs O(1).
Next chapter: 08_sliding_window.md
Chapter 8: Sliding Window
Study time: ~4-5 hours | Prerequisite: Two Pointer (Ch. 7), Arrays | Difficulty: Beginner-Intermediate
1. Introduction
Definition: The Sliding Window technique maintains a contiguous βwindowβ (subarray or substring) defined by two pointers, and slides that window across the data β either at a fixed size or growing/shrinking variably based on a condition β updating an aggregate (sum, count, set of characters, etc.) incrementally rather than recomputing it from scratch at every position.
Purpose: To avoid the O(nΒ·k) (or O(nΒ²)) cost of recomputing a windowβs aggregate from scratch at every position, reducing it to O(n) by incrementally updating the aggregate as the window slides β add what enters, remove what leaves.
Problem solved: βFind the best/valid contiguous subarray/substring satisfying some conditionβ β maximum sum of size k, smallest window containing all required characters, longest substring without repeats, and dozens of variations on this theme.
2. Intuition
Imagine looking through a physical window at a moving train, always seeing exactly 5 cars at a time. As the train moves, you donβt need to recount all 5 visible cars from scratch every second β you just note βone car left view on the left, one new car entered view on the right,β and update your running total accordingly (subtract the car that left, add the car that entered). This is the fixed window idea exactly: maintain a running aggregate, and update it in O(1) per slide instead of recomputing in O(k) every time.
Variable window extends this: instead of a fixed 5-car view, you keep expanding your view (moving the right edge forward) until youβve seen βenoughβ (satisfied some condition), then start contracting from the left to find the smallest view that still satisfies it, giving you the tightest possible window β this two-phase βexpand until valid, then contract while still validβ dance is the core mechanic behind variable-window problems like βsmallest window containing all required characters.β
3. Step-by-Step Working
(a) Fixed Window β max sum of any 3 consecutive elements in [2, 1, 5, 1, 3, 2]
Initial window [0..2]: 2+1+5 = 8. Best so far = 8.
Slide window right by 1 (window [1..3]):
Remove leaving element (2, index 0): 8 - 2 = 6
Add entering element (1, index 3): 6 + 1 = 7
Window sum = 7. Best so far = 8 (unchanged, 7 < 8).
Slide to [2..4]:
Remove arr[1]=1: 7-1=6
Add arr[4]=3: 6+3=9
Window sum = 9. Best so far = 9 (updated!).
Slide to [3..5]:
Remove arr[2]=5: 9-5=4
Add arr[5]=2: 4+2=6
Window sum = 6. Best so far = 9 (unchanged).
Final answer: 9 (from window [2,4] = [5,1,3])
Each slide does exactly 2 operations (one removal, one addition) β O(1) per slide, O(n) total β versus recomputing each windowβs sum from scratch, which would cost O(k) per window and O(nΒ·k) overall.
(b) Variable Window β smallest subarray with sum β₯ 7 in [2, 3, 1, 2, 4, 3]
left=0, right=0, windowSum=0, best=infinity
Expand right, adding elements, until windowSum >= 7:
right=0: windowSum=2
right=1: windowSum=5
right=2: windowSum=6
right=3: windowSum=8 >= 7! β window [0..3], length 4. best=4.
Now CONTRACT from left while still >= 7:
Remove arr[0]=2: windowSum=6 < 7 β stop contracting, left stays at 0...
wait β remove arr[left=0]=2 first, THEN check: windowSum=6, which is < 7, so we
should NOT have contracted past the point where it was still valid. Let's redo
correctly: before removing, window [0..3]=8>=7 is valid, length 4, best=4.
Try contracting: tentatively remove arr[0]=2 β windowSum=6 < 7 β window [1..3]
is now invalid, so we do NOT accept this contraction; left stays at 0 for now,
and we resume EXPANDING right instead.
right=4: windowSum = 6+4 = 10 >= 7 (window [1..4], after the failed contraction
attempt already removed arr[0]) β length 4. Try contracting again:
Remove arr[1]=3: windowSum=7 >= 7! β window [2..4], length 3. best=3. Contract again:
Remove arr[2]=1: windowSum=6 < 7 β stop, window [3..4] invalid.
right=5: windowSum = 6+3 = 9 >= 7 (window [3..5]) β length 3 (tied, best stays 3).
Try contracting: remove arr[3]=2: windowSum=7 >= 7! β window [4..5], length 2. best=2.
Contract again: remove arr[4]=4: windowSum=3 < 7 β stop.
End of array. Final answer: smallest window length = 2 (window [4,5] = [4,3], sum=7)
The key invariant: every time the window becomes valid (sum β₯ 7), we greedily shrink it from the left as much as possible while it remains valid β this greedy shrinking is always safe because a smaller valid window is always at least as good as a larger one for a βsmallest windowβ objective, and we never need to reconsider a left boundary weβve already advanced past.
4. Complexity Analysis
Time: O(n) for both fixed and variable window, despite variable windowβs seemingly more complex βexpand then contractβ dance.
Why fixed window is O(n): the window slides exactly (n - k + 1) times, each slide doing O(1) work (one removal, one addition) β total O(n).
Why variable window is still O(n), not O(nΒ²), despite the nested-looking expand/contract logic: this is the subtle but crucial insight β the right pointer advances at most n times total, and the left pointer also advances at most n times total, across the ENTIRE algorithmβs execution, not per outer iteration. Even though the code has what looks like a loop inside a loop, neither pointer ever moves backward or resets, so the combined total movement of both pointers is bounded by 2n, not nΒ². This is the exact same βeach pointerβs total movement is bounded by nβ argument used for Two Pointer in the previous chapter β Sliding Window is really Two Pointer applied to a contiguous-range problem.
Space: O(1) extra for numeric aggregates (sum, count); O(k) or O(alphabet size) for problems needing a frequency map/set of the windowβs contents (e.g., βlongest substring with at most k distinct charactersβ needs a hash map tracking character counts within the window).
5. Advantages
- Converts what looks like an O(nΒ·k) or O(nΒ²) problem into genuine O(n) by incrementally maintaining an aggregate instead of recomputing it.
- The βexpand/contractβ variable-window pattern handles a surprisingly large class of βsmallest/longest valid subarray/substringβ problems with one consistent mental template.
- Often combines naturally with a hash map (for character/element frequency tracking within the window) without sacrificing the overall O(n) bound.
6. Limitations
- Only applies to contiguous subarrays/substrings β if a problem allows non-contiguous selection, sliding window doesnβt directly apply (thatβs typically a Dynamic Programming or subset-selection problem instead).
- The aggregate being tracked must be efficiently updatable as elements enter/leave the window (O(1) or close to it) β if maintaining the aggregate itself requires expensive recomputation on every change, the technique loses its advantage.
- Variable-window problems require correctly identifying the monotonic relationship between window size and validity (e.g., βgrowing the window can only help/hurt in one directionβ) β misidentifying this can lead to incorrect contraction logic.
7. Real-World Applications
- Networking: TCPβs sliding window protocol for flow control β tracking a moving range of βsent but not yet acknowledgedβ packets, conceptually identical to the fixed-window technique.
- Data Streaming/Analytics: computing running averages, moving maximums, or other rolling statistics over a live data stream (stock price moving averages, sensor data smoothing).
- Text Processing: substring search problems, longest-substring-without-repeats style text analysis (e.g., detecting the longest unique-character run in a log file).
- Video/Audio Processing: frame-based analysis using a sliding temporal window (e.g., detecting motion across a fixed number of consecutive video frames).
- Load Balancing/Rate Limiting: βno more than N requests in any rolling T-second windowβ is a direct sliding-window application in API rate limiters.
- Bioinformatics: scanning DNA sequences with a fixed-size window to detect patterns or compute local statistics (GC content, etc.).
8. C++ Implementation
#include <iostream>
#include <vector>
#include <unordered_map>
#include <climits>
// Fixed Window: maximum sum of any k consecutive elements. O(n).
int maxSumFixedWindow(const std::vector<int>& arr, int k) {
int n = static_cast<int>(arr.size());
if (n < k) return -1; // not enough elements for a window of size k
int windowSum = 0;
for (int i = 0; i < k; ++i) windowSum += arr[i]; // build the FIRST window directly
int best = windowSum;
for (int i = k; i < n; ++i) {
windowSum += arr[i] - arr[i - k]; // add entering element, remove leaving element β O(1)
best = std::max(best, windowSum);
}
return best;
}
// Variable Window: smallest subarray with sum >= target. O(n).
int smallestSubarrayWithSum(const std::vector<int>& arr, int target) {
int n = static_cast<int>(arr.size());
int left = 0, windowSum = 0, best = INT_MAX;
for (int right = 0; right < n; ++right) {
windowSum += arr[right]; // EXPAND: always add the new right-boundary element
while (windowSum >= target) { // CONTRACT: shrink from the left while still valid
best = std::min(best, right - left + 1);
windowSum -= arr[left];
left++;
}
}
return best == INT_MAX ? 0 : best; // 0 (or -1, by convention) if no valid window exists
}
// Variable Window with a hash map: longest substring with at most k distinct characters. O(n).
int longestSubstringKDistinct(const std::string& s, int k) {
std::unordered_map<char, int> freq;
int left = 0, best = 0;
for (int right = 0; right < static_cast<int>(s.size()); ++right) {
freq[s[right]]++; // EXPAND: include the new character
while (static_cast<int>(freq.size()) > k) { // CONTRACT: too many distinct chars, shrink
freq[s[left]]--;
if (freq[s[left]] == 0) freq.erase(s[left]); // remove entirely once count hits 0
left++;
}
best = std::max(best, right - left + 1);
}
return best;
}
// Example usage
int main() {
std::vector<int> arr = {2, 1, 5, 1, 3, 2};
std::cout << "maxSumFixedWindow(k=3): " << maxSumFixedWindow(arr, 3) << "\n"; // 9
std::vector<int> arr2 = {2, 3, 1, 2, 4, 3};
std::cout << "smallestSubarrayWithSum(target=7): " << smallestSubarrayWithSum(arr2, 7) << "\n"; // 2
std::cout << "longestSubstringKDistinct(\"eceba\", k=2): "
<< longestSubstringKDistinct("eceba", 2) << "\n"; // 3 ("ece")
return 0;
}
9. Code Walkthrough
maxSumFixedWindowβs incremental updatewindowSum += arr[i] - arr[i-k]: This single line is the entire point of the technique β rather than resumming k elements at every position (O(k) per window, O(nk) total), we do exactly one subtraction and one addition per slide (O(1) per window, O(n) total).smallestSubarrayWithSumβs nested-lookingwhileinside thefor: As explained in section 4, this is NOT O(nΒ²) despite appearances βleftonly ever increases, and across the whole function call, it increases at most n times total (not n times per outer iteration), so the amortized total work of the innerwhileloop across all outer iterations is O(n), not O(nΒ²).- The βexpand first, then contract while validβ ordering: This ordering is what correctly finds the smallest valid window β we only start contracting once a window becomes valid, and we contract as much as possible before the window becomes invalid again, guaranteeing we donβt miss a smaller valid window at any point.
longestSubstringKDistinctβs frequency map witheraseon zero-count: Removing a character from the map entirely (rather than leaving a zero-count entry) is essential βfreq.size()is used as the βdistinct character countβ check, and a lingering zero-count entry would incorrectly inflate that count.
Common mistakes to watch for here:
- Recomputing the window sum from scratch on every slide instead of using the incremental update β this technically still works but throws away the entire point of the technique (silently degrading back to O(nk)).
- In variable-window problems, contracting the window in the wrong order relative to expanding (e.g., checking validity before adding the new element, rather than after) β leads to off-by-one errors in the final answer.
- Forgetting to erase zero-count entries from a frequency map, corrupting distinct-count checks in problems like
longestSubstringKDistinct.
10. Dry Run
smallestSubarrayWithSum([2,3,1,2,4,3], target=7), condensed trace (matching section 3βs detailed walkthrough):
| right | windowSum after adding | Contract? | left after contracting | best |
|---|---|---|---|---|
| 0 | 2 | no (2<7) | 0 | β |
| 1 | 5 | no (5<7) | 0 | β |
| 2 | 6 | no (6<7) | 0 | β |
| 3 | 8 | yes β remove arr[0]=2, sum=6<7, stop | 1 | 4 |
| 4 | 6+4=10 | yes β remove arr[1]=3, sum=7β₯7, continue β remove arr[2]=1, sum=6<7, stop | 3 | 3 |
| 5 | 6+3=9 | yes β remove arr[3]=2, sum=7β₯7, continue β remove arr[4]=4, sum=3<7, stop | 5 | 2 |
Final answer: 2 β matching section 3βs manual trace exactly. β
11. Complexity Table
| Variant | Time | Space |
|---|---|---|
| Fixed Window | O(n) | O(1) (numeric aggregate) |
| Variable Window (numeric aggregate) | O(n) | O(1) |
| Variable Window (with frequency map) | O(n) | O(k) or O(alphabet size) |
Every entry explained: Fixed windowβs O(n) comes from exactly (n-k+1) O(1) slides. Variable windowβs O(n) comes from the amortized argument in section 4 β both pointersβ total movement across the whole execution is bounded by 2n, never nΒ². The space cost only grows beyond O(1) when the aggregate itself requires more than a single running number (e.g., tracking which distinct characters are present, not just how many).
12. Common Mistakes
- Recomputing the window from scratch on every slide instead of incrementally updating β defeats the entire purpose and silently degrades performance back to O(nk) or worse.
- Misjudging variable-window monotonicity β assuming βgrowing the window always helpsβ when the actual condition doesnβt behave monotonically can lead to incorrect contraction logic (most classic sliding-window problems ARE monotonic in the relevant sense, but always verify this before applying the pattern).
- Off-by-one in window boundaries β particularly around whether
right - left + 1(inclusive-inclusive) is the correct window length formula for your specific pointer convention. - Forgetting to erase zero-count map entries in distinct-count-tracking problems.
- Not handling the βno valid window existsβ edge case β e.g.,
smallestSubarrayWithSummust return a sentinel (0, or -1) rather than leavingbestatINT_MAXif no window ever satisfies the condition.
13. Interview Questions
Conceptual:
- Why is variable-window sliding window O(n) rather than O(nΒ²), despite the code having a loop inside a loop?
- Explain the difference between fixed and variable window, and how to recognize which a given problem needs.
- Why must the aggregate being tracked be efficiently (O(1) or near it) updatable for this technique to pay off?
- Compare Sliding Window to Two Pointer (Chapter 7) β how are they related?
- When does Sliding Window NOT apply β what problem characteristics rule it out?
Coding:
- Maximum Sum Subarray of Size K (fixed window).
- Longest Substring Without Repeating Characters (variable window + set).
- Minimum Window Substring (variable window + frequency map β a harder, classic problem).
- Longest Substring with At Most K Distinct Characters.
- Sliding Window Maximum (needs a monotonic deque β connects back to the Data Structures guideβs Stack/Queue chapter).
- Permutation in String (fixed window + frequency comparison).
Follow-ups / interviewer traps:
- βCan you find the maximum, not just the sum, of every window of size k, still in O(n)?β (expects a monotonic deque β a genuinely different technique than the simple running-sum update, tests whether the candidate over-generalizes the simple fixed-window template)
- βMinimum Window Substring β how do you know when the window is βvalidβ efficiently, without rechecking all required characters every time?β (expects maintaining a βhow many required characters are currently satisfiedβ counter, updated incrementally, rather than a full recheck)
- βWhatβs the space complexity if the alphabet is Unicode rather than ASCII?β (tests awareness that frequency-map-based space costs scale with the actual character set encountered, not a fixed small constant)
14. Practice Problems
Easy
- Maximum Average Subarray I (LeetCode 643) β fixed window
- Contains Duplicate II (LeetCode 219)
Medium
- Longest Substring Without Repeating Characters (LeetCode 3)
- Longest Substring with At Most K Distinct Characters (LeetCode 340)
- Permutation in String (LeetCode 567)
- Fruit Into Baskets (LeetCode 904) β a disguised βat most 2 distinctβ variable window
Hard
- Minimum Window Substring (LeetCode 76)
- Sliding Window Maximum (LeetCode 239)
- Substring with Concatenation of All Words (LeetCode 30)
Also recommended: GeeksforGeeks βSliding Window Techniqueβ practice set, Codeforces problems tagged two pointers (many sliding-window problems are tagged this way, reflecting the close relationship between the two techniques).
15. Summary
Key takeaways:
- Sliding Window is fundamentally Two Pointer applied to a contiguous range problem β incrementally maintaining an aggregate as the window slides, rather than recomputing it from scratch.
- Fixed window slides by a constant amount each step; variable window expands until valid, then contracts while still valid β both achieve O(n) via the same βeach pointerβs total movement is bounded by nβ argument.
- The technique generalizes well beyond simple sums β frequency maps, distinct-element counts, and other efficiently-updatable aggregates all fit the same template.
Complexity recap:
| Time | Space | |
|---|---|---|
| Fixed/Variable Window | O(n) | O(1) to O(k), depending on aggregate complexity |
Decision guide: Reach for Sliding Window whenever a problem asks for a property of contiguous subarrays/substrings β maximum/minimum sum of fixed size, smallest/longest window satisfying a condition, or counting/frequency-based substring properties. If the problem allows non-contiguous selection, this technique doesnβt apply β look toward Dynamic Programming instead.
Next chapter: 09_prefix_sum.md
Chapter 9: Prefix Sum
Study time: ~3-4 hours | Prerequisite: Arrays | Difficulty: Beginner
1. Introduction
Definition: A Prefix Sum array precomputes, for each index i, the sum of all elements from the start of the array up to and including i. Once built, the sum of any range [L, R] can be answered in O(1) via a single subtraction, instead of re-summing the range each time.
Purpose: To answer repeated range-sum queries in O(1) each, after a one-time O(n) preprocessing pass β trading a small amount of upfront work and O(n) extra space for dramatically faster queries.
Problem solved: βGiven an array, answer many queries of the form βwhatβs the sum of elements from index L to R?ββ β naively O(n) per query (O(nΒ·q) for q queries), reduced to O(n) total preprocessing + O(1) per query (O(n+q) total).
2. Intuition
If you know the running total of your bank account balance after every single transaction (a βprefix sumβ of all deposits/withdrawals), you can answer βhow much did I spend between transaction 5 and transaction 20?β instantly β just subtract balance-after-5 from balance-after-20 β without re-adding every individual transaction in that range. This is the entire idea: precompute cumulative totals once, then any rangeβs total is just a difference of two cumulative totals.
prefixSum[i] = arr[0] + arr[1] + ... + arr[i]
sum(L, R) = prefixSum[R] - prefixSum[L-1] (or prefixSum[R] if L==0)
Why this works: prefixSum[R] includes everything from 0 to R.
prefixSum[L-1] includes everything from 0 to L-1.
Subtracting removes exactly the "0 to L-1" portion, leaving exactly "L to R."
3. Step-by-Step Working
Array [2, 4, 5, 7, 8, 9]. Build prefix sum:
arr: [2, 4, 5, 7, 8, 9]
prefixSum: [2, 6, 11, 18, 26, 35]
β β β β β β
arr[0] arr[0..1] arr[0..2] ... arr[0..5]
(prefixSum[i] = prefixSum[i-1] + arr[i], with prefixSum[0] = arr[0])
Query sum(1, 4) (elements at indices 1 through 4 β 4+5+7+8 = 24):
sum(1,4) = prefixSum[4] - prefixSum[0] = 26 - 2 = 24 β
Query sum(0, 5) (the whole array β 2+4+5+7+8+9 = 35):
sum(0,5) = prefixSum[5] = 35 (no subtraction needed when L=0)
2D Prefix Sum β the same idea extended to a matrix, for range-sum queries over rectangular submatrices:
matrix: 2D prefix sum (each cell = sum of the rectangle from (0,0) to (i,j)):
1 2 3 1 3 6
4 5 6 5 12 21
7 8 9 12 27 45
To query the sum of the rectangle from (r1,c1) to (r2,c2), use inclusion-exclusion:
sum = P[r2][c2] - P[r1-1][c2] - P[r2][c1-1] + P[r1-1][c1-1]
(whole rect) (remove top) (remove left) (add back double-removed corner)
The +P[r1-1][c1-1] term is necessary because subtracting both the βtopβ and βleftβ strips double-subtracts their overlapping corner region β adding it back once corrects for this, the same inclusion-exclusion principle used throughout combinatorics.
4. Complexity Analysis
Build: O(n) for 1D (a single pass, each prefixSum[i] computed from prefixSum[i-1] in O(1)); O(nΒ·m) for a 2D array of size nΓm (each cell computed in O(1) from three previously-computed neighbors).
Query: O(1) for 1D (one subtraction); O(1) for 2D (four array lookups + inclusion-exclusion arithmetic) β regardless of how large the queried range/rectangle is.
Why O(1) query is possible: all the βhard workβ of summing is done exactly once, upfront, during the build phase β every query afterward is just reading two (or four, for 2D) precomputed values and combining them arithmetically, never re-traversing the actual range being queried.
Total for q queries: O(n + q) β compare this to the naive O(nΒ·q) of re-summing each range from scratch every time. For a million queries on a million-element array, this is the difference between ~10^12 operations (infeasible) and ~2Γ10^6 operations (instant).
Space: O(n) extra for 1D, O(nΒ·m) for 2D β the precomputed prefix array itself.
5. Advantages
- O(1) range-sum queries after O(n) preprocessing β a dramatic speedup for any workload with many repeated range queries on static (unchanging) data.
- Simple to implement and reason about β a single pass to build, simple arithmetic to query.
- Generalizes cleanly to 2D (and higher dimensions) via inclusion-exclusion.
- The same underlying idea generalizes beyond sums β prefix XOR, prefix min/max (with caveats β see limitations), prefix product, and other associative operations can use analogous precomputation.
6. Limitations
- Only efficient for static data β if the underlying array changes frequently (point updates), the prefix sum array would need to be rebuilt (or partially updated) on every change, losing the O(1) query advantage unless paired with a more sophisticated structure (a Fenwick Tree or Segment Tree β see the Data Structures guide, Chapters 15-16 β for O(log n) updates alongside O(log n) or O(1) queries).
- Doesnβt generalize to non-invertible operations β prefix min or max cannot be βsubtractedβ the way sum can (thereβs no way to recover
min(L,R)frommin(0,R)andmin(0,L-1)in general), so the simple prefix-sum-style range query trick doesnβt extend to min/max queries; those need a different structure (Sparse Table for static data, or Segment Tree for dynamic). - 2D prefix sums require careful inclusion-exclusion arithmetic β an easy source of off-by-one bugs, especially around the boundary rows/columns.
7. Real-World Applications
- Databases: materialized aggregate/rollup tables for fast range-based analytical queries (e.g., βtotal sales between date X and Yβ) are conceptually prefix-sum-based.
- Image Processing: βintegral imagesβ (2D prefix sums of pixel intensities) enable O(1) computation of the sum of any rectangular region β used heavily in real-time computer vision algorithms (e.g., the Viola-Jones face detection algorithm relies on integral images for fast feature computation).
- Finance: cumulative return/balance calculations, computing sum/average over arbitrary date ranges from a precomputed running total.
- Analytics Dashboards: any βsum/count over a custom date rangeβ feature backed by precomputed cumulative aggregates.
- Game Development: precomputed cumulative probability distributions for weighted random selection (build a prefix sum of weights, then binary search β directly combining Chapter 1 and this chapter).
- Competitive Programming: an extremely common building-block technique, often combined with binary search, two pointers, or hashing to solve more complex range-based problems.
8. C++ Implementation
#include <iostream>
#include <vector>
// 1D Prefix Sum. O(n) build, O(1) per query.
class PrefixSum1D {
private:
std::vector<long long> prefix;
public:
explicit PrefixSum1D(const std::vector<int>& arr) {
prefix.resize(arr.size());
prefix[0] = arr[0];
for (size_t i = 1; i < arr.size(); ++i) {
prefix[i] = prefix[i - 1] + arr[i]; // each cell built from the previous in O(1)
}
}
// Sum of arr[L..R] inclusive. O(1).
long long rangeSum(int L, int R) const {
if (L == 0) return prefix[R];
return prefix[R] - prefix[L - 1];
}
};
// 2D Prefix Sum. O(n*m) build, O(1) per query.
class PrefixSum2D {
private:
std::vector<std::vector<long long>> prefix;
public:
explicit PrefixSum2D(const std::vector<std::vector<int>>& matrix) {
int rows = static_cast<int>(matrix.size());
int cols = static_cast<int>(matrix[0].size());
prefix.assign(rows, std::vector<long long>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
long long top = (i > 0) ? prefix[i - 1][j] : 0;
long long left = (j > 0) ? prefix[i][j - 1] : 0;
long long topLeft = (i > 0 && j > 0) ? prefix[i - 1][j - 1] : 0;
// inclusion-exclusion: add top strip + left strip, subtract double-counted corner
prefix[i][j] = matrix[i][j] + top + left - topLeft;
}
}
}
// Sum of the rectangle from (r1,c1) to (r2,c2) inclusive. O(1).
long long rangeSum(int r1, int c1, int r2, int c2) const {
long long total = prefix[r2][c2];
long long top = (r1 > 0) ? prefix[r1 - 1][c2] : 0;
long long left = (c1 > 0) ? prefix[r2][c1 - 1] : 0;
long long topLeft = (r1 > 0 && c1 > 0) ? prefix[r1 - 1][c1 - 1] : 0;
return total - top - left + topLeft; // inclusion-exclusion again, in reverse
}
};
// Example usage
int main() {
std::vector<int> arr = {2, 4, 5, 7, 8, 9};
PrefixSum1D ps(arr);
std::cout << "sum(1,4): " << ps.rangeSum(1, 4) << "\n"; // 24
std::cout << "sum(0,5): " << ps.rangeSum(0, 5) << "\n"; // 35
std::vector<std::vector<int>> matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
PrefixSum2D ps2d(matrix);
std::cout << "rectSum(0,0,1,1): " << ps2d.rangeSum(0, 0, 1, 1) << "\n"; // 1+2+4+5=12
std::cout << "rectSum(1,1,2,2): " << ps2d.rangeSum(1, 1, 2, 2) << "\n"; // 5+6+8+9=28
return 0;
}
9. Code Walkthrough
PrefixSum1Dβs build loop: Eachprefix[i]is computed asprefix[i-1] + arr[i]β O(1) work per index, O(n) total, since each cell only ever looks at its immediate predecessor.rangeSumβsL == 0special case: Without this check,prefix[L-1]would beprefix[-1], an out-of-bounds access β the special case handles the fact that βeverything before index 0β has a sum of 0, which isnβt naturally representable asprefix[-1].PrefixSum2Dβs build formula (matrix[i][j] + top + left - topLeft): This is inclusion-exclusion in action βtopandlefteach independently include thetopLeftcorner region, so naively adding both would double-count it; subtractingtopLeftonce corrects for exactly that overcounting.PrefixSum2D::rangeSumβs four-term formula: The mirror image of the build formula β start with the full rectangle from the origin to(r2,c2), subtract the excess βtopβ strip and βleftβ strip, then add backtopLeftonce since it was subtracted twice (once as part of each strip).- Using
long longinstead ofint: Prefix sums can grow large even when individual elements are small (a sum of a million elements each up to 1000 could reach a billion, strainingintβs range) β using a wider type is a defensive habit worth having by default for any accumulating sum.
Common mistakes to watch for here:
- Forgetting the
L == 0(orr1==0/c1==0) boundary special cases, causing out-of-bounds access. - Sign errors in the 2D inclusion-exclusion formula (forgetting to subtract
topLeft, or adding instead of subtracting a term) β always re-derive this formula from first principles rather than memorizing it verbatim if unsure. - Using
intinstead of a wider type for large arrays/value ranges, risking silent overflow. - Rebuilding the entire prefix sum array on every single point update instead of recognizing that this workload calls for a Fenwick Tree or Segment Tree instead (Data Structures guide, Chapters 15-16).
10. Dry Run
2D query rangeSum(1,1,2,2) on the matrix from section 8 (prefix table computed in section 3):
prefix table:
1 3 6
5 12 21
12 27 45
rangeSum(r1=1,c1=1,r2=2,c2=2):
total = prefix[2][2] = 45
top = prefix[0][2] = 6 (r1-1=0)
left = prefix[2][0] = 12 (c1-1=0)
topLeft = prefix[0][0] = 1 (r1-1=0, c1-1=0)
result = 45 - 6 - 12 + 1 = 28
Verify directly: the rectangle from (1,1) to (2,2) covers matrix values 5,6,8,9 β sum = 5+6+8+9 = 28. β
11. Complexity Table
| Operation | Time | Space |
|---|---|---|
| Build (1D) | O(n) | O(n) |
| Build (2D) | O(nΒ·m) | O(nΒ·m) |
| Query (1D or 2D) | O(1) | β |
| Naive re-sum per query (for comparison) | O(range size) | O(1) |
Every entry explained: Build cost is linear (or the 2D equivalent) because each cell is computed once from a small, fixed number of already-computed neighbors β no cell is ever revisited. Query cost is O(1) precisely because it never touches the original range at all, only the small, fixed number of precomputed boundary values β this decoupling of βone-time preprocessing costβ from βper-query costβ is the entire value proposition of the technique.
12. Common Mistakes
- Off-by-one errors at range boundaries, especially the
L==0/r1==0/c1==0special cases. - Sign errors in the 2D inclusion-exclusion formula β always sanity-check against a small hand-computed example (as in section 10) when in doubt.
- Applying prefix sum to frequently-updated data without recognizing that a Fenwick Tree or Segment Tree is the appropriate tool once updates enter the picture.
- Attempting to extend the technique naively to min/max queries β subtraction-based range recovery fundamentally doesnβt work for non-invertible operations; a different structure (Sparse Table, Segment Tree) is needed instead.
- Integer overflow from not using a sufficiently wide type for large cumulative sums.
13. Interview Questions
Conceptual:
- Why does Prefix Sum achieve O(1) query time, and whatβs the total cost across n build operations plus q queries compared to naive re-summing?
- Why doesnβt the prefix-sum trick work for range minimum or maximum queries the way it works for sums?
- Explain the inclusion-exclusion principle behind the 2D prefix sum query formula.
- When would you use a Fenwick Tree instead of a plain Prefix Sum array?
- How does an βintegral imageβ in computer vision relate to 2D prefix sums?
Coding:
- Implement 1D and 2D Prefix Sum from scratch.
- Range Sum Query - Immutable (LeetCode 303) β the direct 1D application.
- Range Sum Query 2D - Immutable (LeetCode 304) β the direct 2D application.
- Subarray Sum Equals K (LeetCode 560) β prefix sum combined with a hash map for O(n) counting.
- Product of Array Except Self (LeetCode 238) β a prefix/suffix product variant of the same idea.
- Continuous Subarray Sum (LeetCode 523) β prefix sum + modular arithmetic.
Follow-ups / interviewer traps:
- βThe array now needs point updates β does your Prefix Sum approach still work efficiently?β (no β expects recognizing that a Fenwick Tree or Segment Tree is now the right tool, since naive prefix sum rebuild is O(n) per update)
- βCan you count subarrays summing to exactly K in O(n)?β (expects combining prefix sums with a hash map tracking βhow many times has this prefix sum value been seen beforeβ β a very common and elegant technique)
- βWhy doesnβt this technique work for range GCD or range XOR the same way it works for sum?β (XOR is actually invertible β same trick works via
prefixXor[R] ^ prefixXor[L-1]β but GCD is not; tests whether the candidate understands which operations are invertible, not just memorizing βsum worksβ)
14. Practice Problems
Easy
- Range Sum Query - Immutable (LeetCode 303)
- Running Sum of 1d Array (LeetCode 1480)
- Find Pivot Index (LeetCode 724)
Medium
- Range Sum Query 2D - Immutable (LeetCode 304)
- Subarray Sum Equals K (LeetCode 560)
- Product of Array Except Self (LeetCode 238)
- Continuous Subarray Sum (LeetCode 523)
Hard
- Maximum Size Subarray Sum Equals K (related prefix-sum + hash map problem)
- Count of Range Sum (LeetCode 327) β combines prefix sum with merge sort or a BIT/Segment Tree
Also recommended: GeeksforGeeks βPrefix Sum Arrayβ practice set; implement the βcount subarrays summing to Kβ pattern from scratch, as itβs one of the most widely reused prefix-sum + hash map combinations in interview problem sets.
15. Summary
Key takeaways:
- Prefix Sum trades O(n) one-time preprocessing for O(1) range-sum queries β ideal for static data with many repeated range queries.
- The technique fundamentally relies on sum being invertible (subtraction recovers a sub-range) β it does not generalize to non-invertible operations like min/max without a different underlying structure.
- 2D prefix sums use inclusion-exclusion, a pattern worth internalizing since it recurs throughout combinatorics and range-query problems generally.
Complexity recap:
| Time | Space | |
|---|---|---|
| Build | O(n) [1D] / O(nΒ·m) [2D] | O(n) / O(nΒ·m) |
| Query | O(1) | β |
Decision guide: Reach for Prefix Sum whenever you have static data and need to answer many range-sum (or other invertible-operation) queries efficiently. If the data needs frequent updates, move to a Fenwick Tree or Segment Tree (Data Structures guide, Chapters 15-16) instead β same query-speed philosophy, but supporting O(log n) updates that plain Prefix Sum cannot handle efficiently.
Next chapter: 10_greedy_algorithms.md
Chapter 10: Greedy Algorithms
Study time: ~6-7 hours | Prerequisite: Sorting (Ch. 2-4), basic proof intuition | Difficulty: Intermediate
1. Introduction
Definition: A Greedy Algorithm builds a solution step by step, at each step making the choice that looks locally best at that moment, and never revisiting or reconsidering that choice later β betting that a sequence of locally optimal choices produces a globally optimal result.
Purpose: To solve optimization problems dramatically faster than exhaustive search (often O(n log n) instead of exponential), but only for problems where local optimality provably implies global optimality β a property that must be proven, not assumed.
Problem solved: A specific class of optimization problems (scheduling, resource allocation, encoding) where a well-chosen greedy rule, applied consistently, is provably guaranteed to reach the best possible overall outcome.
2. Intuition
Imagine making change for $0.67 using US coins (quarters, dimes, nickels, pennies) β the natural approach is to grab the largest coin that doesnβt overshoot the remaining amount, repeatedly: 25+25+10+5+1+1 = 67 cents, using 6 coins. This βalways grab the biggest piece that fitsβ strategy is greedy, and for the standard US coin system, itβs provably optimal β no other combination uses fewer coins. But this isnβt true for every coin system β with coins {1, 3, 4}, greedily making 6 cents grabs a 4 first, then two 1s (4+1+1=3 coins), when 3+3=2 coins is actually better. This is the central lesson of greedy algorithms: the strategy is only as good as the proof behind it β it can look almost identical for a problem where it works and one where it silently fails.
The two most common proof techniques for βwhy does greedy work here?β:
- Exchange Argument: show that if an optimal solution doesnβt include the greedy choice, you can always βexchangeβ some other element in it for the greedy choice without making the solution worse β proving the greedy choice could always have been included safely.
- Matroid / Cut Property structure: certain problems have an underlying mathematical structure (a matroid, or in graph problems, the βcut propertyβ β see the Data Structures guideβs MST chapter) that guarantees greedy choices are safe, by theorem.
3. Step-by-Step Working
(a) Activity Selection β maximize the number of non-overlapping activities
Activities (start, end): (1,4), (3,5), (0,6), (5,7), (3,9), (5,9), (6,10), (8,11), (8,12), (2,14), (12,16)
GREEDY RULE: sort by END TIME, always pick the next activity whose start time is
β₯ the end time of the last picked activity.
Sorted by end time: (1,4),(3,5),(0,6),(5,7),(3,9),(5,9),(6,10),(8,11),(8,12),(2,14),(12,16)
Pick (1,4). lastEnd=4.
(3,5): start=3 < 4 β SKIP (overlaps)
(0,6): start=0 < 4 β SKIP
(5,7): start=5 >= 4 β PICK. lastEnd=7.
(3,9): start=3 < 7 β SKIP
(5,9): start=5 < 7 β SKIP
(6,10): start=6 < 7 β SKIP
(8,11): start=8 >= 7 β PICK. lastEnd=11.
(8,12): start=8 < 11 β SKIP
(2,14): start=2 < 11 β SKIP
(12,16): start=12 >= 11 β PICK. lastEnd=16.
Selected: (1,4), (5,7), (8,11), (12,16) β 4 non-overlapping activities, PROVABLY the maximum possible.
Why βsort by end timeβ specifically works (exchange argument sketch): picking the activity that finishes earliest always leaves the most possible room for future activities β if an optimal solution picked some other first activity that finishes later, you could always swap it for the earliest-finishing one without reducing the count of activities that still fit afterward. This exchange never makes things worse, which is exactly the exchange-argument proof pattern.
(b) Huffman Coding β build an optimal prefix-free binary encoding
Character frequencies: A:5, B:9, C:12, D:13, E:16, F:45
Repeatedly extract the TWO smallest-frequency nodes, merge them into a new node
(frequency = sum), reinsert, until one node remains (using a Min-Heap β direct
application of the Data Structures guide's Heap chapter):
Extract 5(A), 9(B) β merge β new node 14, reinsert. Heap: {12,13,14,16,45}
Extract 12(C), 13(D) β merge β new node 25, reinsert. Heap: {14,16,25,45}
Extract 14, 16(E) β merge β new node 30, reinsert. Heap: {25,30,45}
Extract 25, 30 β merge β new node 55, reinsert. Heap: {45,55}
Extract 45(F), 55 β merge β new node 100 (root). Heap: {100} β done.
Resulting tree gives shorter codes to more frequent characters (F, frequency 45,
gets the shortest code; A, frequency 5, gets one of the longest) β minimizing
total encoded length across the whole message.
4. Complexity Analysis
Activity Selection: O(n log n) β dominated by the initial sort by end time; the greedy selection pass itself is a single O(n) linear scan afterward.
Huffman Coding: O(n log n) β n-1 extract-min operations from a heap of up to n elements, each O(log n) (directly reusing the Heap chapterβs complexity analysis from the Data Structures guide).
General pattern: most greedy algorithms cost O(n log n), dominated by an initial sort (to process elements in the βrightβ order for the greedy rule to apply correctly) plus a linear O(n) greedy pass β this is why greedy algorithms are typically much faster than the Dynamic Programming alternatives they sometimes compete with (which are often O(nΒ²) or worse), when a valid greedy strategy actually exists for the problem.
5. Advantages
- Typically much faster than Dynamic Programming or exhaustive search for problems where a valid greedy strategy exists β often O(n log n) versus O(nΒ²) or exponential.
- Simple to implement once the correct greedy rule is identified β usually just βsort, then scan.β
- Elegant, provable optimality (via exchange argument or matroid structure) gives strong confidence in correctness, unlike heuristics that merely βusually work well.β
6. Limitations
- Only works when local optimality provably implies global optimality β applying a greedy strategy to a problem that doesnβt have this property produces a plausible-looking but genuinely wrong (suboptimal) answer, often without any obvious signal that something went wrong.
- Finding the correct greedy rule (and proving it correct) is itself a nontrivial skill β many candidate greedy strategies for a given problem are subtly wrong, and problems can have multiple βreasonable-lookingβ greedy rules where only one is actually correct.
- Cannot be βpatchedβ the way Dynamic Programming can β DP naturally handles problems where choices interact and must be reconsidered; Greedy fundamentally cannot revisit a choice once made, so if thatβs genuinely required, greedy is the wrong tool entirely, not just a suboptimal one.
7. Real-World Applications
- Operating Systems: Shortest Job First / Shortest Remaining Time First CPU scheduling (a direct Activity-Selection-style greedy strategy).
- Networking: Huffman Coding is the basis of many real compression formats (DEFLATE, used in gzip/PNG, uses Huffman coding as one of its stages); Dijkstraβs algorithm (Data Structures guide, Chapter 14) is itself a greedy algorithm (always expand the closest known vertex next).
- Finance: Fractional Knapsack-style greedy strategies for portfolio allocation under simplified (divisible-asset) assumptions.
- Compilers: Register allocation sometimes uses greedy graph-coloring heuristics (though this specific application is a heuristic, not a provably-optimal greedy algorithm, illustrating the important distinction covered in the limitations section).
- Databases: Query optimization sometimes uses greedy heuristics for join-order selection (again, typically a heuristic rather than provably optimal, since the underlying problem is NP-hard in general).
- Data Compression: Huffman Coding remains foundational to many modern compression schemes as a component alongside more advanced techniques.
- Game Development: greedy pathfinding heuristics (though full shortest-path correctness typically needs Dijkstra/A*, which are themselves greedy-with-a-heap algorithms).
8. C++ Implementation
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
// ---------- ACTIVITY SELECTION ----------
struct Activity {
int start, end;
};
// Greedy: sort by end time, pick each activity whose start >= last picked end. O(n log n).
std::vector<Activity> activitySelection(std::vector<Activity> activities) {
std::sort(activities.begin(), activities.end(),
[](const Activity& a, const Activity& b) { return a.end < b.end; });
std::vector<Activity> selected;
int lastEnd = -1;
for (const Activity& a : activities) {
if (a.start >= lastEnd) { // no overlap with the last selected activity
selected.push_back(a);
lastEnd = a.end;
}
}
return selected;
}
// ---------- HUFFMAN CODING ----------
struct HuffmanNode {
char ch;
int freq;
HuffmanNode* left;
HuffmanNode* right;
HuffmanNode(char c, int f, HuffmanNode* l = nullptr, HuffmanNode* r = nullptr)
: ch(c), freq(f), left(l), right(r) {}
};
struct Compare {
bool operator()(HuffmanNode* a, HuffmanNode* b) { return a->freq > b->freq; } // min-heap by frequency
};
// Build the Huffman tree. O(n log n) β n-1 extract-min + insert operations on a heap.
HuffmanNode* buildHuffmanTree(const std::vector<std::pair<char,int>>& freqs) {
std::priority_queue<HuffmanNode*, std::vector<HuffmanNode*>, Compare> pq;
for (auto& [ch, freq] : freqs) {
pq.push(new HuffmanNode(ch, freq));
}
while (pq.size() > 1) {
HuffmanNode* left = pq.top(); pq.pop(); // two smallest-frequency nodes
HuffmanNode* right = pq.top(); pq.pop();
HuffmanNode* merged = new HuffmanNode('\0', left->freq + right->freq, left, right);
pq.push(merged); // reinsert the merged node
}
return pq.top(); // the root of the completed Huffman tree
}
// Traverse the tree to generate each character's binary code. O(n) over the tree's nodes.
void generateCodes(HuffmanNode* node, const std::string& code, std::vector<std::pair<char,std::string>>& result) {
if (!node) return;
if (!node->left && !node->right) { // leaf node β represents an actual character
result.push_back({node->ch, code.empty() ? "0" : code}); // handle single-character edge case
return;
}
generateCodes(node->left, code + "0", result);
generateCodes(node->right, code + "1", result);
}
// Example usage
int main() {
std::vector<Activity> activities = {
{1,4},{3,5},{0,6},{5,7},{3,9},{5,9},{6,10},{8,11},{8,12},{2,14},{12,16}
};
auto selected = activitySelection(activities);
std::cout << "Selected activities: ";
for (auto& a : selected) std::cout << "(" << a.start << "," << a.end << ") ";
std::cout << "\n"; // (1,4) (5,7) (8,11) (12,16)
std::vector<std::pair<char,int>> freqs = {{'A',5},{'B',9},{'C',12},{'D',13},{'E',16},{'F',45}};
HuffmanNode* root = buildHuffmanTree(freqs);
std::vector<std::pair<char,std::string>> codes;
generateCodes(root, "", codes);
std::cout << "Huffman codes:\n";
for (auto& [ch, code] : codes) std::cout << " " << ch << ": " << code << "\n";
// More frequent characters (like F=45) get shorter codes than rare ones (like A=5)
return 0;
}
9. Code Walkthrough
activitySelectionβs sort-by-end-time: This specific sort key is the entire correctness argument from section 3βs exchange-argument sketch β sorting by start time or by duration instead would produce a plausible-looking but provably suboptimal greedy algorithm; end time is the one sort key that makes the greedy choice provably safe.lastEndtracking: A single variable suffices to track the greedy state β no need to look back at all previously selected activities, only the most recent one, since activities are processed in sorted end-time order and the greedy choice only ever needs to compare against the most recently committed choice.buildHuffmanTreeβs min-heap ofHuffmanNode*: This is a direct, unmodified application of the Heap data structure (Data Structures guide, Chapter 5) β the greedy rule (βalways merge the two least-frequent remaining nodesβ) is implemented entirely through repeated extract-min/insert operations, with no additional logic needed beyond what the heap itself provides.generateCodesβs recursive traversal: Building the code string by appending β0β for left and β1β for right as it descends is what produces a valid prefix-free code β no characterβs code is ever a prefix of anotherβs, which is exactly the tree-structural guarantee that makes Huffman-encoded data unambiguously decodable.- The
code.empty() ? "0" : codespecial case: Handles the edge case of a single-character alphabet (only one node, so the tree is a single leaf with no traversal at all) β without this, that character would get an empty code, which is meaningless.
Common mistakes to watch for here:
- Sorting activities by start time or duration instead of end time β a very common, plausible-looking, but provably incorrect variant.
- Forgetting to handle ties in Huffmanβs min-heap comparator (though any consistent tie-breaking still produces a valid, optimal β if not unique β encoding).
- Not freeing the dynamically allocated
HuffmanNodetree after use (a real memory-management concern in production code, simplified away here for clarity).
10. Dry Run
Already traced in full detail in section 3 for both algorithms β Activity Selection selecting (1,4), (5,7), (8,11), (12,16) (4 activities, provably maximal), and Huffman Coding progressively merging {5,9}β14, {12,13}β25, {14,16}β30, {25,30}β55, {45,55}β100, building a tree where frequency-45 character F ends up with a short code and frequency-5 character A ends up with a longer one.
11. Complexity Table
| Algorithm | Time | Space |
|---|---|---|
| Activity Selection | O(n log n) | O(n) or O(1) if sorting in-place |
| Huffman Coding | O(n log n) | O(n) for the tree + heap |
| Fractional Knapsack | O(n log n) | O(1) extra beyond sorting |
Every entry explained: All three follow the same pattern β an O(n log n) sort (or heap-based equivalent) to establish the correct processing order, followed by an O(n) (or O(n log n) for repeated heap operations, as in Huffman) linear-ish pass applying the greedy rule. The sort/heap cost dominates in every case, which is why βO(n log n), dominated by sortingβ is such a common refrain across greedy algorithms generally.
12. Common Mistakes
- Assuming greedy works without proving it β the single most dangerous mistake in this entire chapter; a greedy strategy that βseems reasonableβ can be silently wrong, producing a plausible but suboptimal answer with no obvious red flag.
- Choosing the wrong sort key β as shown in Activity Selection, sorting by the βobviously relatedβ criterion (start time) instead of the actually-correct one (end time) is an extremely common error.
- Applying greedy to a Coin-Change-style problem with a non-canonical coin system β the classic counterexample (coins {1,3,4}, target 6) where greedy fails and Dynamic Programming is required instead.
- Confusing βa greedy algorithm exists for this problemβ with βany greedy rule worksβ β many different greedy rules can be proposed for the same problem, and usually only one (or a small few) is actually correct.
- Not considering whether choices interact β if selecting one element changes the desirability of a later choice in a way the greedy rule doesnβt account for, thatβs a signal the problem likely needs Dynamic Programming instead.
13. Interview Questions
Conceptual:
- What must be true about a problem for a greedy algorithm to be provably correct?
- Explain the exchange argument proof technique, using Activity Selection as an example.
- Give an example of a greedy strategy that looks correct but isnβt (the Coin Change counterexample is the classic one β walk through why it fails).
- Why is Huffman Codingβs result guaranteed optimal (minimum expected code length) for a given set of character frequencies?
- Compare Greedy and Dynamic Programming β whatβs the key structural difference that determines which applies?
Coding:
- Activity Selection Problem.
- Fractional Knapsack Problem.
- Huffman Coding β build the tree and generate codes.
- Job Sequencing with Deadlines.
- Minimum Number of Platforms Required (interval scheduling variant).
- Gas Station (LeetCode 134) β a non-obvious greedy problem requiring a clever proof.
Follow-ups / interviewer traps:
- βProve your greedy strategy is actually optimal, not just plausible.β (the single most important thing an interviewer can ask in this entire chapter β always be ready to sketch an exchange argument or cite the relevant matroid/cut-property structure)
- βWhat if the coin denominations arenβt {1,5,10,25} β does greedy still work for making change?β (tests recognizing that greedy correctness for Coin Change depends on the specific denomination system being βcanonical,β not a general guarantee)
- βCan you solve Fractional Knapsack with Dynamic Programming instead β would that even make sense?β (tests understanding that Fractional Knapsackβs greedy correctness comes from the ability to take partial items, a structural property that the 0/1 Knapsack variant β which genuinely needs DP β lacks)
14. Practice Problems
Easy
- Assign Cookies (LeetCode 455)
- Lemonade Change (LeetCode 860)
Medium
- Jump Game (LeetCode 55) β greedy reachability tracking
- Gas Station (LeetCode 134)
- Task Scheduler (LeetCode 621) β connects back to the Data Structures guideβs Heap chapter
- Non-overlapping Intervals (LeetCode 435) β Activity Selection in disguise
- Partition Labels (LeetCode 763)
Hard
- Candy (LeetCode 135) β a two-pass greedy proof
- Job Sequencing with Deadlines (GeeksforGeeks classic)
- Minimum Number of Arrows to Burst Balloons (LeetCode 452)
Also recommended: for every greedy problem you solve, explicitly write out (even informally) why the greedy choice is safe β this habit is what separates βgot lucky with a plausible strategyβ from genuine understanding, and itβs exactly what a good interviewer is listening for.
15. Summary
Key takeaways:
- Greedy algorithms make irrevocable locally-optimal choices, and are only correct when that local optimality is provably sufficient for global optimality β via an exchange argument, matroid structure, or cut-property-style reasoning.
- The classic failure mode (Coin Change with non-canonical denominations) is not a corner case to memorize and forget β itβs a permanent reminder that a greedy strategy must always be justified, never merely assumed because it βfeels right.β
- When greedy applies, itβs typically the fastest correct approach available (O(n log n)), dramatically outperforming the Dynamic Programming alternative that would otherwise be needed for problems where choices genuinely interact.
Complexity recap:
| Time | Space | |
|---|---|---|
| Typical Greedy Algorithm | O(n log n) | O(n) or O(1) extra |
Decision guide: Reach for Greedy when you can articulate (and ideally prove) why the locally best choice at each step can never be wrong for the overall objective. The moment you find yourself unable to justify why an earlier choice couldnβt be regretted given later information, thatβs the signal to switch to Dynamic Programming (next chapter after Backtracking) instead.
Next chapter: 11_backtracking.md
Chapter 11: Backtracking
Study time: ~6-7 hours | Prerequisite: Recursion, basic understanding of state-space search | Difficulty: Intermediate
1. Introduction
Definition: Backtracking is a systematic method for exploring all possible configurations of a problem by building a solution incrementally, one choice at a time, and abandoning (βbacktrackingβ from) a partial configuration the moment itβs discovered to be invalid β rather than continuing to build on top of a doomed choice.
Purpose: To search a combinatorial space (permutations, subsets, board configurations) exhaustively but efficiently, by pruning away entire branches of the search tree as soon as theyβre known to be invalid, instead of generating every full configuration and checking it at the end.
Problem solved: βFind one (or all) valid configuration(s) satisfying a set of constraintsβ β N-Queens, Sudoku, generating permutations/subsets/combinations, and any problem shaped like βmake a sequence of choices, some combinations of which are invalid.β
2. Intuition
Imagine navigating a maze by trying each possible direction at every junction, and the moment you hit a dead end, walking back to the last junction and trying a different direction instead of giving up entirely. This is backtracking exactly: explore, and the instant a choice leads somewhere invalid, undo it and try the next option β never wasting time fully completing a path you already know is doomed.
The key structural insight: backtracking is recursion with two extra ingredients β (1) a way to make a choice, recurse, and then undo that choice before trying the next option (so sibling branches donβt see stale state from a previous branch), and (2) a pruning check that abandons a branch as soon as itβs provably invalid, rather than only checking validity once a full configuration is built.
3. Step-by-Step Working
(a) Generating all subsets of {1, 2, 3}
Decision at each element: INCLUDE it or EXCLUDE it. Recursion tree:
{}
/ \
include 1 exclude 1
{1} {}
/ \ / \
incl 2 excl 2 incl 2 excl 2
{1,2} {1} {2} {}
/ \ / \ / \ / \
incl3 excl3 incl3 excl3 incl3 excl3 incl3 excl3
{1,2,3}{1,2} {1,3} {1} {2,3} {2} {3} {}
All 8 (=2Β³) leaves are the complete power set:
{}, {3}, {2}, {2,3}, {1}, {1,3}, {1,2}, {1,2,3}
No pruning is needed here (every subset is βvalidβ), but this tree structure β make a choice, recurse into both branches, implicitly βundoβ by simply returning β is the skeleton every backtracking problem builds on.
(b) N-Queens (N=4) β place 4 queens on a 4Γ4 board so none attack each other
Place queens row by row. At each row, try each column; check if it's SAFE
(no queen in the same column, or same diagonal, as any already-placed queen).
If safe, place and recurse to the next row. If the recursive call fails to
find a full solution, UNDO (remove the queen) and try the next column.
Row 0: try col 0 β place. Row 1: try col 0 β SAME COLUMN as row 0, invalid.
try col 1 β SAME DIAGONAL as row 0's queen (row0,col0)-(row1,col1), invalid.
try col 2 β safe! place. Row 2: try col 0 β same column as row0, invalid.
try col 1 β diagonal with row1's queen, invalid.
try col 2 β same column as row1, invalid.
try col 3 β diagonal with row0? (0,0)-(2,3)? no. diagonal with row1?
(1,2)-(2,3)? YES diagonal, invalid.
ALL columns fail for row 2 β BACKTRACK to row 1.
Row 1: try col 3 β safe (not same col/diag as row0's (0,0)). place.
Row 2: try col 0 β same col as row0, invalid.
try col 1 β diagonal with row1's (1,3)? no... continue checking β
eventually finds col 1 is safe. place.
Row 3: try each column, find one safe from all three previous queens.
...continuing this process (with further backtracks as needed) eventually yields:
Solution: (0,1), (1,3), (2,0), (3,2) β one of the 2 valid solutions for N=4.
The critical efficiency insight: the moment row 2 has NO safe column given rows 0-1βs placement, we immediately abandon that entire subtree (we never even consider row 3 at all) β this pruning is what separates backtracking from brute-force generate-all-then-check, which would waste enormous time completing full (but doomed) board configurations.
4. Complexity Analysis
General time complexity: O(b^d) where b is the branching factor (choices per step) and d is the depth (number of decisions) β this is the size of the full search tree if NO pruning occurred at all.
Why pruning matters so much in practice, despite not changing the worst-case Big-O: for many real problems (N-Queens, Sudoku), the actual number of nodes explored is dramatically smaller than b^d because invalid branches are abandoned early, often just one or two levels deep β this doesnβt change the theoretical worst-case bound (which assumes an adversarial input where pruning rarely helps), but itβs the difference between βinstantβ and βcomputationally infeasibleβ for typical/practical inputs.
Subsets/Permutations generation: generating all 2^n subsets is inherently Ξ(2^n) (there are exactly that many subsets to output, so you canβt do better); generating all n! permutations is inherently Ξ(n!) β these arenβt cases where pruning helps reduce the count of outputs, only cases where backtracking provides a clean, correct way to enumerate them without redundant work.
Space: O(d) for the recursion stack (one call frame per decision level) β backtrackingβs memory footprint is proportional to the depth of the search, not the breadth, since only one path through the tree is βactiveβ (on the call stack) at any given moment.
5. Advantages
- Systematically explores an entire combinatorial search space with a guarantee of correctness (finds a valid solution if one exists, or all solutions if thatβs the goal).
- Pruning can turn a theoretically exponential search into a practically fast one for many real problem instances β often the difference between infeasible and instant.
- The βchoose, recurse, undoβ template is highly reusable β once learned, it applies to a huge range of superficially different problems (permutations, subsets, board games, path-finding with constraints).
6. Limitations
- Worst-case time remains exponential (O(b^d)) β pruning helps in practice but provides no asymptotic guarantee for adversarial inputs.
- Easy to introduce subtle bugs by forgetting to βundoβ a choice before trying the next option β this corrupts sibling branches with stale state from a previous branch.
- Not suitable for optimization problems with overlapping subproblems (where the same sub-configuration is reached via multiple different paths) β that scenario calls for Dynamic Programming instead, which can memoize and avoid redundant recomputation that backtracking alone would repeat.
7. Real-World Applications
- Constraint Satisfaction Systems: Sudoku solvers, scheduling systems with hard constraints (no two conflicting events at the same time/resource).
- Compilers: Type inference and certain parsing algorithms use backtracking-style exploration when multiple parse interpretations are possible.
- Games/Puzzles: Solving/generating puzzles (crosswords, Sudoku, N-Queens-style placement puzzles) and implementing game-tree search for simple combinatorial games.
- Circuit Design/VLSI: Component placement and routing problems with hard constraints sometimes use backtracking-based search.
- Natural Language Processing: Certain parsing algorithms (e.g., for context-free grammars) use backtracking to explore ambiguous parse trees.
- Robotics/Path Planning: Exploring possible movement sequences under hard constraints (obstacles, resource limits) in simplified/discretized planning problems.
- AI: Classic AI search problems (constraint satisfaction problems, CSPs) are directly modeled and solved via backtracking with various pruning heuristics (forward checking, arc consistency).
8. C++ Implementation
#include <iostream>
#include <vector>
#include <string>
// Generate all subsets of a set. O(2^n) β inherent to the output size.
void generateSubsets(std::vector<int>& nums, int index, std::vector<int>& current,
std::vector<std::vector<int>>& result) {
if (index == static_cast<int>(nums.size())) {
result.push_back(current); // reached the end β record this complete subset
return;
}
// CHOICE 1: exclude nums[index]
generateSubsets(nums, index + 1, current, result);
// CHOICE 2: include nums[index]
current.push_back(nums[index]);
generateSubsets(nums, index + 1, current, result);
current.pop_back(); // UNDO β critical, so the next sibling call sees clean state
}
// N-Queens: return true if a solution exists, filling `board` with column positions per row.
bool isSafe(const std::vector<int>& board, int row, int col) {
for (int prevRow = 0; prevRow < row; ++prevRow) {
int prevCol = board[prevRow];
if (prevCol == col) return false; // same column
if (std::abs(prevCol - col) == std::abs(prevRow - row)) return false; // same diagonal
}
return true;
}
bool solveNQueens(std::vector<int>& board, int row, int n) {
if (row == n) return true; // all n queens placed successfully
for (int col = 0; col < n; ++col) {
if (isSafe(board, row, col)) {
board[row] = col; // CHOICE: place queen at (row, col)
if (solveNQueens(board, row + 1, n)) {
return true; // found a full solution β propagate success up
}
board[row] = -1; // UNDO (backtrack) β this placement didn't lead to a solution
}
}
return false; // no column in this row works β signal failure to the caller, which will also backtrack
}
// Example usage
int main() {
std::vector<int> nums = {1, 2, 3};
std::vector<int> current;
std::vector<std::vector<int>> subsets;
generateSubsets(nums, 0, current, subsets);
std::cout << "All subsets of {1,2,3}:\n";
for (auto& s : subsets) {
std::cout << "{ ";
for (int x : s) std::cout << x << " ";
std::cout << "}\n";
}
int n = 4;
std::vector<int> board(n, -1);
if (solveNQueens(board, 0, n)) {
std::cout << "\n4-Queens solution (column per row): ";
for (int col : board) std::cout << col << " ";
std::cout << "\n"; // e.g., 1 3 0 2
}
return 0;
}
9. Code Walkthrough
generateSubsetsβs two recursive calls (exclude, then include): This is the βchoose, recurse, undoβ template in its purest form β for each element, we explore BOTH the βnot in the subsetβ branch and the βin the subsetβ branch, and crucially,current.pop_back()undoes the inclusion before the function returns, ensuring the parentβs next sibling call (or the parent itself continuing) seescurrentexactly as it was before this call started.- Why the
pop_back()placement matters: if it were missing, every subsequent subset generated after the first βincludeβ branch would incorrectly retain that element β this single line is what prevents state from leaking between sibling branches in the recursion tree. isSafeβs column and diagonal checks: Same column is checked directly (prevCol == col); same diagonal is checked via the classicabs(prevCol - col) == abs(prevRow - row)trick β two cells are on the same diagonal exactly when their row difference equals their column difference in absolute value. No need to check βsame rowβ explicitly, since we only ever place one queen per row by construction.solveNQueensβsboard[row] = -1undo: After a recursive call fails to complete a solution, resettingboard[row]to βunplacedβ is the explicit backtracking step β without it,isSafechecks for later rows could be misled by a βphantomβ queen placement thatβs no longer actually part of the current candidate solution.- The
if (solveNQueens(...)) return true;early-exit: Once a valid full solution is found, we propagatetrueall the way back up through every recursive call frame, avoiding any further unnecessary exploration β critical for βfind any one solutionβ problems (versus βfind all solutions,β which would instead continue exploring after each success).
Common mistakes to watch for here:
- Forgetting to undo a choice (
pop_back(), resetting a board cell, etc.) before trying the next option β this is the single most common backtracking bug, and it silently corrupts results in ways that can be hard to spot. - Checking validity only at the very end (after a full configuration is built) instead of pruning early β this technically still works but throws away most of backtrackingβs practical performance benefit.
- Confusing βfind one solutionβ (early-exit on success) with βfind all solutionsβ (must continue exploring even after finding one) β these require different control flow.
10. Dry Run
generateSubsets({1,2}, ...), full recursion trace:
| Call | index | current before | Action | current after |
|---|---|---|---|---|
| generateSubsets(0) | 0 | [] | exclude nums[0]=1 β recurse | [] |
| β generateSubsets(1) | 1 | [] | exclude nums[1]=2 β recurse | [] |
| β β generateSubsets(2) | 2 | [] | index==size β RECORD {} | β |
| β (back) include nums[1]=2 | 1 | [] | push 2 β [2] β recurse | [2] |
| β β generateSubsets(2) | 2 | [2] | index==size β RECORD {2} | β |
| β (back) pop β [] | 1 | [2]β[] | undo, return | [] |
| (back at index 0) include nums[0]=1 | 0 | [] | push 1 β [1] β recurse | [1] |
| β generateSubsets(1) | 1 | [1] | exclude nums[1]=2 β recurse | [1] |
| β β generateSubsets(2) | 2 | [1] | RECORD {1} | β |
| β include nums[1]=2 β [1,2] β recurse | 1 | [1,2] | RECORD {1,2} | β |
| β pop β [1] | undo | [1] | ||
| (back) pop β [] | 0 | [1]β[] | undo, return | [] |
Final subsets recorded, in order: {}, {2}, {1}, {1,2} β all 4 (=2Β²) subsets of {1,2}, confirming the pattern from section 3 scales correctly. β
11. Complexity Table
| Problem | Time (worst case) | Space |
|---|---|---|
| Generate all subsets | Ξ(2βΏ) | O(n) recursion depth |
| Generate all permutations | Ξ(n!) | O(n) recursion depth |
| N-Queens | O(n!) worst case (loose bound; pruning makes actual runtime far smaller) | O(n) recursion depth |
| Sudoku | O(9^(number of empty cells)) worst case (extremely loose; constraint propagation prunes drastically in practice) | O(number of empty cells) |
Every entry explained: Subsets/permutations have their complexity fixed by the sheer number of valid outputs (thereβs no way to enumerate 2βΏ subsets in better than Ξ(2βΏ), since you must at minimum output each one). N-Queens and Sudokuβs stated worst-case bounds are extremely loose upper bounds assuming essentially no effective pruning β in practice, the constraint checks (isSafe, Sudokuβs row/column/box rules) prune the vast majority of the naive search tree, making real-world runtime dramatically better than the loose theoretical bound suggests.
12. Common Mistakes
- Forgetting to undo a choice before the next sibling branch β the most common and most subtle backtracking bug, since the code often still βrunsβ without crashing, just silently produces wrong results.
- Checking constraints only at the end instead of pruning incrementally β loses most of the practical performance benefit that makes backtracking viable for problems like N-Queens or Sudoku at meaningful sizes.
- Confusing βany one solutionβ vs. βall solutionsβ control flow β using early-exit (
return truepropagation) when all solutions are actually needed, or vice versa. - Not recognizing when a problem actually needs Dynamic Programming instead β if the same sub-configuration is reachable via multiple different decision paths (overlapping subproblems), plain backtracking will redundantly re-explore it every time, where DP would memoize and reuse the result.
- Off-by-one or incorrect base-case conditions, causing the recursion to either terminate too early (missing valid configurations) or never terminate (infinite recursion).
13. Interview Questions
Conceptual:
- What are the two essential ingredients of backtracking beyond plain recursion?
- Why doesnβt pruning change the worst-case Big-O, and why does it matter anyway in practice?
- Compare Backtracking and Dynamic Programming β what problem characteristic determines which is appropriate?
- Explain why N-Queensβ βsame diagonalβ check works with the
abs(row difference) == abs(col difference)formula. - Whatβs the difference in control flow between βfind any one valid solutionβ and βfind all valid solutionsβ?
Coding:
- Generate all subsets of a set (Power Set).
- Generate all permutations of an array.
- N-Queens β return one solution, or count all solutions.
- Sudoku Solver.
- Combination Sum β find all combinations summing to a target (allows repeated elements).
- Word Search β find if a word exists in a grid via backtracking DFS.
- Generate Parentheses β all valid combinations of n pairs of parentheses.
Follow-ups / interviewer traps:
- βCan you optimize N-Queens further with additional pruning (e.g., tracking used columns/diagonals in O(1) sets instead of scanning previous rows)?β (tests awareness of further optimization beyond the basic correct-but-simple approach)
- βCombination Sum β how do you avoid generating duplicate combinations?β (tests understanding of sorting + skip-duplicate-at-same-level logic, a common refinement)
- βWord Search β why do you need to βun-markβ a visited cell after backtracking?β (tests the same undo-the-choice principle applied to grid traversal rather than array/board state)
14. Practice Problems
Easy
- Subsets (LeetCode 78)
- Binary Watch (LeetCode 401)
Medium
- Permutations (LeetCode 46)
- Combination Sum (LeetCode 39)
- Generate Parentheses (LeetCode 22)
- Word Search (LeetCode 79)
- Palindrome Partitioning (LeetCode 131)
Hard
- N-Queens (LeetCode 51) / N-Queens II (LeetCode 52, count only)
- Sudoku Solver (LeetCode 37)
- Word Search II (LeetCode 212) β combines backtracking with a Trie (Data Structures guide, Ch. 9)
Also recommended: GeeksforGeeks βBacktrackingβ practice set, Codeforces problems tagged dfs and similar + brute force for additional practice recognizing when pruning-heavy exhaustive search applies.
15. Summary
Key takeaways:
- Backtracking = recursion + (a) explicit choice/undo bookkeeping and (b) early pruning of invalid branches β the undo step is what prevents state from leaking between sibling branches.
- Worst-case complexity remains exponential, but pruning can make real-world performance dramatically better than the loose theoretical bound suggests.
- The line between Backtracking and Dynamic Programming is overlapping subproblems: if the same sub-configuration can be reached multiple ways and is worth memoizing, thatβs DPβs territory, not backtrackingβs.
Complexity recap:
| Time (worst case) | Space | |
|---|---|---|
| Backtracking (general) | O(b^d) | O(d) |
Decision guide: Reach for Backtracking when you need to enumerate all valid configurations, or find any one configuration satisfying hard constraints, and thereβs no meaningful overlap between different branches of the search (each decision path is essentially independent). The moment you notice the same sub-state recurring across different decision paths and being worth caching, thatβs your signal to move to Dynamic Programming (next chapter) instead.
Next chapter: 12_dynamic_programming_fundamentals.md
Chapter 12: Dynamic Programming β Fundamentals
Study time: ~8-10 hours | Prerequisite: Recursion, Backtracking (Ch. 11) | Difficulty: Advanced
1. Introduction
Definition: Dynamic Programming (DP) solves a problem by breaking it into overlapping subproblems, solving each unique subproblem only once, and storing (caching) its result for reuse β converting what would otherwise be exponential repeated recomputation into polynomial time.
Purpose: To recognize and exploit overlapping subproblems β cases where plain recursion (or backtracking) would solve the exact same smaller subproblem many times over β and eliminate that redundant work via memoization or tabulation.
Problem solved: Optimization (min/max), counting, or feasibility problems where the natural recursive formulation revisits the same subproblem repeatedly β Fibonacci-style sequences, Knapsack, Longest Common Subsequence, Coin Change, and hundreds of variations.
2. Intuition
Consider computing the 5th Fibonacci number recursively: fib(5) = fib(4) + fib(3), but fib(4) = fib(3) + fib(2) β notice fib(3) gets computed twice, once directly for fib(5) and once inside fib(4)βs computation. As n grows, this redundancy explodes exponentially (the naive recursive Fibonacci is O(2βΏ)), even though there are only n+1 distinct subproblems (fib(0) through fib(n)) β all that repeated work is solving the same handful of problems over and over.
The core DP insight: if youβre about to solve a subproblem, first check βhave I already solved this exact subproblem before?β If yes, reuse the cached answer instantly (O(1)); if no, solve it once and cache the result for next time. This single idea β recognize repeated subproblems, solve each exactly once β converts Fibonacci from O(2βΏ) to O(n), and does the same transformation for a huge class of related problems.
Two ways to implement this idea:
- Memoization (Top-Down): write the natural recursive solution, but wrap it with a cache β before computing, check the cache; after computing, store the result. This mirrors how youβd naturally think about the problem (start from the goal, recurse toward the base case).
- Tabulation (Bottom-Up): iteratively build up a table of subproblem answers, starting from the base cases and working toward the final answer β no recursion at all, just careful iteration order.
3. Step-by-Step Working
(a) Fibonacci β Memoization vs. Tabulation vs. Space-Optimized
NAIVE RECURSION (no caching) β exponential, recomputes fib(3) twice, fib(2) three
times, etc., for fib(5):
fib(5)
βββ fib(4)
β βββ fib(3)
β β βββ fib(2) β computed here
β β βββ fib(1)
β βββ fib(2) β RECOMPUTED here β wasted work
βββ fib(3) β RECOMPUTED here β wasted work
βββ fib(2) β RECOMPUTED again
βββ fib(1)
MEMOIZATION (top-down): same recursive shape, but check/fill a cache first:
memo = {}
fib(5) β not in memo β compute fib(4)+fib(3)
fib(4) β not in memo β compute fib(3)+fib(2)
fib(3) β not in memo β compute fib(2)+fib(1)
fib(2) β not in memo β compute fib(1)+fib(0) = 1+0 = 1 β CACHE memo[2]=1
fib(1) β base case β 1
fib(3) = 1+1 = 2 β CACHE memo[3]=2
fib(2) β ALREADY IN MEMO β return 1 instantly, no recomputation!
fib(4) = 2+1 = 3 β CACHE memo[4]=3
fib(3) β ALREADY IN MEMO β return 2 instantly!
fib(5) = 3+2 = 5 β CACHE memo[5]=5
Total unique subproblems solved: fib(0) through fib(5) β exactly 6, not the
exponentially-many redundant calls the naive version made.
TABULATION (bottom-up): build a table iteratively, no recursion:
dp[0]=0, dp[1]=1
dp[2] = dp[1]+dp[0] = 1
dp[3] = dp[2]+dp[1] = 2
dp[4] = dp[3]+dp[2] = 3
dp[5] = dp[4]+dp[3] = 5
SPACE-OPTIMIZED: notice dp[i] only ever needs dp[i-1] and dp[i-2] β no need to
keep the WHOLE table, just the last two values:
prev2=0, prev1=1
i=2: curr=1, shift: prev2=1,prev1=1
i=3: curr=2, shift: prev2=1,prev1=2
i=4: curr=3, shift: prev2=2,prev1=3
i=5: curr=5, shift: prev2=3,prev1=5
Result: 5, using O(1) space instead of O(n).
(b) 0/1 Knapsack β a 2D state-space example
Items: (weight, value) = (2,3), (3,4), (4,5), (5,6). Capacity = 5.
STATE: dp[i][w] = maximum value achievable using the first i items, with
capacity limit w.
TRANSITION at each item: either SKIP it (dp[i-1][w]) or, if it fits (weight <= w),
TAKE it (value + dp[i-1][w - weight]) β take whichever is better:
dp[i][w] = max( dp[i-1][w], // skip item i
(weight[i] <= w) ? value[i] + dp[i-1][w-weight[i]] : -infinity ) // take item i
Building the table (rows = items considered so far, cols = capacity 0..5):
w=0 w=1 w=2 w=3 w=4 w=5
no items: 0 0 0 0 0 0
+(2,3): 0 0 3 3 3 3
+(3,4): 0 0 3 4 4 7
+(4,5): 0 0 3 4 5 7
+(5,6): 0 0 3 4 5 7
Final answer: dp[4][5] = 7 (achieved by taking items (2,3) and (3,4): weight 2+3=5, value 3+4=7)
Why this is DP and not just backtracking: the same subproblem dp[i][w] (e.g., βbest value using the first 2 items with capacity 3β) might be reached via multiple different decision paths in a naive recursive exploration β DP recognizes this and computes each distinct (i, w) pairβs answer exactly once, storing it for reuse, rather than re-deriving it every time itβs needed.
4. Complexity Analysis
Fibonacci: Naive recursion O(2βΏ) time, O(n) space (call stack). Memoization/Tabulation: O(n) time, O(n) space (or O(1) with the space-optimized rolling-variables version).
0/1 Knapsack: O(nΒ·W) time and space, where n = number of items, W = capacity β this is the size of the dp[i][w] table, and each cell is computed in O(1) from at most two previously-computed cells.
General DP complexity formula: O(number of distinct states Γ cost to compute each stateβs transition). This is the formula to derive complexity for any new DP problem you encounter β first identify how many distinct (parameters) combinations exist (the state space size), then multiply by how much work each individual transition costs.
Why DP complexity is usually much better than naive recursionβs: naive recursionβs cost is (number of leaf calls in the recursion tree), which can be exponential even when the number of distinct subproblems is only polynomial β DPβs entire value proposition is collapsing βexponentially many redundant callsβ down to βpolynomially many unique subproblems, each solved once.β
5. Advantages
- Converts exponential naive recursion into polynomial time whenever overlapping subproblems exist β often the difference between βcomputationally infeasibleβ and βinstant.β
- The systematic βdefine state, define transition, define base caseβ methodology generalizes to an enormous range of problems once internalized.
- Space-optimization (rolling variables, as in Fibonacci) frequently reduces memory from O(n) or O(nΒ·m) down to O(1) or O(m), once you recognize that only a small, fixed window of previous states is ever needed.
6. Limitations
- Requires correctly identifying the state (what parameters uniquely define a subproblem) and the transition (how to compute a state from smaller/previously-solved states) β this is a genuine skill that takes deliberate practice, and getting the state definition wrong leads to either incorrect results or a solution that doesnβt actually collapse the redundant work.
- Memoizationβs recursive implementation risks stack overflow for very deep recursion (mirroring the same concern raised for recursive tree/graph traversal in the Data Structures guide).
- Not every problem with βchoicesβ has overlapping subproblems β if every decision path leads to a genuinely distinct subproblem (no overlap), DP provides no advantage over plain backtracking/recursion, and the added bookkeeping (cache management) is pure overhead.
7. Real-World Applications
- Bioinformatics: DNA/protein sequence alignment (edit distance, longest common subsequence) is fundamentally a DP problem, foundational to tools like BLAST.
- Finance: option pricing models (binomial tree models) and certain portfolio optimization formulations use DP.
- Operations Research: resource allocation, inventory management, and scheduling problems with additive/multiplicative cost structures are classic DP applications.
- Compilers: optimal instruction selection and certain register allocation subproblems use DP-based approaches.
- Networking: certain routing cost-optimization problems (though many practical routing algorithms are greedy/Dijkstra-based, some optimal offline variants use DP).
- Natural Language Processing: Viterbi algorithm (used in speech recognition and part-of-speech tagging) is a direct DP application over sequences.
- Game Development/AI: many turn-based game evaluation strategies use DP-based memoization over game states.
- Version Control: the
diffalgorithm computing minimal edit sequences between file versions is a Longest Common Subsequence-style DP problem.
8. C++ Implementation
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
// ---------- FIBONACCI: three implementations for comparison ----------
// Memoization (Top-Down). O(n) time, O(n) space.
long long fibMemo(int n, std::unordered_map<int, long long>& memo) {
if (n <= 1) return n;
if (memo.count(n)) return memo[n]; // already solved β reuse instantly
long long result = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
memo[n] = result; // cache before returning
return result;
}
// Tabulation (Bottom-Up). O(n) time, O(n) space.
long long fibTabulation(int n) {
if (n <= 1) return n;
std::vector<long long> dp(n + 1);
dp[0] = 0; dp[1] = 1;
for (int i = 2; i <= n; ++i) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
// Space-Optimized. O(n) time, O(1) space.
long long fibOptimized(int n) {
if (n <= 1) return n;
long long prev2 = 0, prev1 = 1;
for (int i = 2; i <= n; ++i) {
long long curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
}
return prev1;
}
// ---------- 0/1 KNAPSACK ----------
// O(n * W) time and space.
int knapsack01(const std::vector<int>& weights, const std::vector<int>& values, int capacity) {
int n = static_cast<int>(weights.size());
std::vector<std::vector<int>> dp(n + 1, std::vector<int>(capacity + 1, 0));
for (int i = 1; i <= n; ++i) {
for (int w = 0; w <= capacity; ++w) {
dp[i][w] = dp[i - 1][w]; // option 1: skip item i-1 (0-indexed weights/values)
if (weights[i - 1] <= w) {
dp[i][w] = std::max(dp[i][w], values[i - 1] + dp[i - 1][w - weights[i - 1]]); // option 2: take it
}
}
}
return dp[n][capacity];
}
// Example usage
int main() {
std::unordered_map<int, long long> memo;
std::cout << "fib(30) memoized: " << fibMemo(30, memo) << "\n";
std::cout << "fib(30) tabulated: " << fibTabulation(30) << "\n";
std::cout << "fib(30) optimized: " << fibOptimized(30) << "\n"; // all three: 832040
std::vector<int> weights = {2, 3, 4, 5};
std::vector<int> values = {3, 4, 5, 6};
std::cout << "0/1 Knapsack (capacity=5): " << knapsack01(weights, values, 5) << "\n"; // 7
return 0;
}
9. Code Walkthrough
fibMemoβs cache check (if (memo.count(n))): This single check is what prevents the exponential blowup β every time a subproblem would otherwise be recomputed, this line intercepts it and returns the cached answer in O(1) instead.fibMemocaching AFTER computing, BEFORE returning: The order matters β the cache must be populated before the function returns, so that any other call frame (a sibling in the recursion tree) that later needsfib(n)finds it already cached.fibTabulationβs iteration order (ifrom 2 up to n): Bottom-up DP requires computing subproblems in an order that guarantees every dependency (dp[i-1],dp[i-2]) is already computed before itβs needed β this is the βfigure out the correct iteration orderβ challenge mentioned as tabulationβs main extra difficulty versus memoization.fibOptimizedβs rolling variables: Recognizing thatdp[i]only ever depends on the two immediately preceding values (never anything further back) is what allows collapsing an O(n)-space table down to two O(1) variables β this pattern (looking at a DP transition and asking βhow far back do I actually need to look?β) is one of the most valuable space-optimization skills in this entire chapter.knapsack01βs two-optiondp[i][w]transition: Directly implements the recurrence from section 3(b) βdp[i][w]is always the better of βdonβt take item iβ (dp[i-1][w]) and βtake item i, if it fitsβ (values[i-1] + dp[i-1][w-weights[i-1]]). Thei-1indexing throughout reflects thatdpuses 1-indexed βnumber of items consideredβ whileweights/valuesarrays are 0-indexed β a common source of off-by-one confusion worth tracing carefully.
Common mistakes to watch for here:
- Forgetting to cache a computed result in memoization (or caching before, rather than after, computing β which would cache an incomplete/wrong value).
- Getting tabulationβs iteration order wrong, referencing a
dpcell that hasnβt been computed yet. - Off-by-one errors in Knapsackβs 1-indexed-items-vs-0-indexed-arrays indexing.
- Attempting the space optimization (rolling variables) before verifying which previous states a transition actually depends on β collapsing too aggressively can silently produce wrong answers if a transition needs more history than the optimization preserves.
10. Dry Run
knapsack01 table build, fully shown in section 3(b). Tracing just the final row transition for item (5,6) at w=5:
dp[4][5] = max( dp[3][5], // skip (5,6): dp[3][5] = 7
weights[3]=5 <= 5 ? values[3] + dp[3][5-5] : skip )
= max( 7, 6 + dp[3][0] )
= max( 7, 6 + 0 )
= max( 7, 6 )
= 7
Item (5,6) doesnβt improve on the existing best of 7 (from items (2,3)+(3,4)) β confirming the tableβs final entry dp[4][5] = 7 is correctly derived from its two possible predecessor states.
11. Complexity Table
| Problem | Time | Space (naive) | Space (optimized) |
|---|---|---|---|
| Fibonacci | O(n) | O(n) | O(1) |
| 0/1 Knapsack | O(nΒ·W) | O(nΒ·W) | O(W) β since each row only needs the previous row |
Every entry explained: Fibonacciβs O(n) comes from exactly n+1 distinct subproblems, each computed once in O(1) from its predecessors. Knapsackβs O(nΒ·W) comes from the table having exactly (n+1)Γ(W+1) cells, each computed in O(1) β the space optimization to O(W) is possible because, just like Fibonacci, row i of the Knapsack table only ever depends on row i-1, never anything further back, so only the most recent row needs to be retained (a very common DP space-optimization pattern worth recognizing generally).
12. Common Mistakes
- Attempting DP without first identifying the state clearly β jumping straight to code without articulating βwhat does
dp[i](ordp[i][j]) actually represent?β is the single most common source of DP bugs. - Forgetting to cache in memoization, silently reverting to exponential naive recursion despite superficially βhavingβ a memo table.
- Wrong iteration order in tabulation, referencing not-yet-computed table cells.
- Premature space optimization before confirming exactly which previous states a transition depends on.
- Confusing βoptimal substructure existsβ with βoverlapping subproblems existβ β DP needs BOTH properties; a problem can have optimal substructure (like plain divide-and-conquer, e.g., Merge Sort) without overlapping subproblems, in which case memoization provides no benefit at all.
13. Interview Questions
Conceptual:
- What are the two necessary properties (overlapping subproblems + optimal substructure) for DP to apply, and how do you check for each?
- Compare memoization and tabulation β when would you prefer one over the other?
- Why is naive recursive Fibonacci O(2βΏ) but memoized Fibonacci O(n)? Walk through the exact mechanism.
- How do you recognize when a DP tableβs space usage can be optimized (rolling array technique)?
- Give an example of a problem with optimal substructure but NOT overlapping subproblems β why wouldnβt DP help there?
Coding:
- Implement Fibonacci three ways (naive, memoized, tabulated, space-optimized) and benchmark them.
- 0/1 Knapsack.
- Climbing Stairs (LeetCode 70) β a Fibonacci-shaped DP in disguise.
- House Robber (LeetCode 198) β a 1D DP with a simple two-state transition.
- Minimum Path Sum in a grid (2D DP, directly analogous to Knapsackβs table structure).
Follow-ups / interviewer traps:
- βCan you reduce your Knapsack solutionβs space from O(nW) to O(W)?β (expects recognizing the rolling-row optimization, iterating capacity in the correct β often reverse β order to avoid overwriting values still needed within the same row)
- βYour memoized solution works but stack-overflows for large n β how do you fix it?β (expects converting to tabulation, which removes recursion entirely)
- βWhatβs the difference between this problem and one thatβs solvable with plain divide-and-conquer (like Merge Sort) without any memoization?β (tests the overlapping-subproblems distinction directly)
14. Practice Problems
Easy
- Climbing Stairs (LeetCode 70)
- Fibonacci Number (LeetCode 509)
- Min Cost Climbing Stairs (LeetCode 746)
Medium
- House Robber (LeetCode 198)
- House Robber II (LeetCode 213) β circular variant
- Coin Change (LeetCode 322) β previewed here, full treatment in the next chapter
- Unique Paths (LeetCode 62)
- Minimum Path Sum (LeetCode 64)
Hard
- 0/1 Knapsack (GeeksforGeeks classic; not directly on LeetCode as a standalone problem, but underlies many harder problems)
- Partition Equal Subset Sum (LeetCode 416) β a Knapsack variant
- Target Sum (LeetCode 494) β a Knapsack-shaped counting problem
Also recommended: for every DP problem, explicitly write out the state definition and transition BEFORE coding β this habit dramatically reduces bugs and is exactly what strong interview candidates do out loud.
15. Summary
Key takeaways:
- DP applies when a problem has BOTH overlapping subproblems (the same smaller problem recurs across different decision paths) AND optimal substructure (the optimal solution can be built from optimal solutions to subproblems).
- Memoization (top-down, cache-as-you-recurse) and Tabulation (bottom-up, iteratively fill a table) solve the same underlying problem two different ways β memoization mirrors natural recursive thinking; tabulation avoids recursion entirely and often allows further space optimization.
- The βrolling variablesβ space-optimization pattern (Fibonacci needing only the last 2 values, Knapsack needing only the last row) recurs constantly once you know to look for it.
Complexity recap:
| Time | Space (before optimization) | |
|---|---|---|
| DP (general) | O(states Γ transition cost) | O(number of states) |
Decision guide: Reach for DP the moment you notice a recursive/backtracking solution re-solving the identical subproblem multiple times β thatβs the unmistakable signal. If every recursive call explores a genuinely distinct subproblem with zero overlap, plain recursion or backtracking is already optimal, and adding memoization would only add overhead with no benefit.
Next chapter: 13_dynamic_programming_classic_problems.md β Knapsack variants, LCS, LIS, Coin Change, and the broader DP pattern library.
Chapter 13: Dynamic Programming β Classic Problems (LCS, LIS, Coin Change)
Study time: ~8-9 hours | Prerequisite: DP Fundamentals (Ch. 12) | Difficulty: Advanced
1. Introduction
Definition: This chapter covers three of the most widely-applicable DP problem shapes β Longest Common Subsequence (LCS, a 2D string/sequence-alignment DP), Longest Increasing Subsequence (LIS, a 1D sequence DP with two different solution approaches of different complexity), and Coin Change (an unbounded-knapsack-shaped counting/optimization DP) β each a template that dozens of other interview problems are secretly variations of.
Purpose: To build a working library of recognizable DP patterns, since a huge fraction of real DP interview questions are disguised variants of these three underlying shapes rather than genuinely novel problems.
Problem solved: Sequence alignment/comparison (LCS β diffing files, DNA matching), finding structure within a sequence (LIS β trend detection, patience sorting), and optimal combination-counting under repeatable choices (Coin Change β the unbounded knapsack family).
2. Intuition
LCS: given two sequences, find the longest sequence of characters that appears in both, in order (not necessarily contiguous). The natural recursive question at any pair of positions (i, j): βif the current characters match, they must be part of the LCS β extend by 1 and recurse on the rest of both strings. If they donβt match, the LCS must come from either skipping a character in the first string or skipping one in the second β try both, take the better.β This branching, applied at every position pair, is exactly the 2D dp[i][j] state Knapsack-style problems use.
LIS: given a sequence, find the longest subsequence thatβs strictly increasing. The naive recursive question at position i: βfor every earlier position j with a smaller value, could I extend that increasing subsequence by including position i?β β this gives an O(nΒ²) DP directly. A cleverer O(n log n) approach (patience sorting, named after the card game) maintains a list of βsmallest possible tail value for an increasing subsequence of each length,β updated via binary search (directly reusing Chapter 1) as you scan the sequence.
Coin Change: given a set of coin denominations (each usable an unlimited number of times β hence βunbounded,β unlike 0/1 Knapsackβs βeach item at most onceβ), find the minimum number of coins summing to a target (or count the number of ways). The natural recursive question at amount a: βfor each coin denomination c β€ a, what if I use one of that coin? The remaining problem is exactly the same shape, just for amount a - cβ β this self-similarity (the subproblem for a smaller amount looks exactly like the original problem) is the hallmark of unbounded-knapsack-style DP.
3. Step-by-Step Working
(a) Longest Common Subsequence β βABCBDABβ and βBDCABAβ
STATE: dp[i][j] = length of LCS of the first i characters of string1 and
the first j characters of string2.
TRANSITION:
if string1[i-1] == string2[j-1]: dp[i][j] = dp[i-1][j-1] + 1 (extend the match)
else: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) (skip one char from either)
Building the table (rows = string1 "ABCBDAB", cols = string2 "BDCABA"):
"" B D C A B A
"" 0 0 0 0 0 0 0
A 0 0 0 0 1 1 1
B 0 1 1 1 1 2 2
C 0 1 1 2 2 2 2
B 0 1 1 2 2 3 3
D 0 1 2 2 2 3 3
A 0 1 2 2 3 3 4
B 0 1 2 2 3 4 4
Final answer: dp[7][6] = 4 (one valid LCS: "BCBA" or "BDAB", both length 4)
Reconstructing the actual subsequence (not just its length) requires walking backward through the table from dp[n][m]: whenever string1[i-1]==string2[j-1], that character is part of the LCS, move diagonally to dp[i-1][j-1]; otherwise, move toward whichever of dp[i-1][j] or dp[i][j-1] was larger.
(b) Longest Increasing Subsequence β [10, 9, 2, 5, 3, 7, 101, 18]
O(nΒ²) APPROACH: dp[i] = length of the longest increasing subsequence ENDING at index i.
dp[0]=1 (just [10])
dp[1]=1 (just [9], since 9 < 10 can't extend anything before it)
dp[2]=1 (just [2])
dp[3]: check all j<3 with arr[j]<arr[3]=5: arr[2]=2<5 β dp[3]=dp[2]+1=2 ([2,5])
dp[4]: check j<4 with arr[j]<3: arr[2]=2<3 β dp[4]=dp[2]+1=2 ([2,3])
dp[5]: check j<5 with arr[j]<7: arr[2]=2,arr[3]=5,arr[4]=3 all <7 β best is dp[3]=2 β dp[5]=3 ([2,5,7])
dp[6]: check j<6 with arr[j]<101: ALL qualify β best is dp[5]=3 β dp[6]=4 ([2,5,7,101])
dp[7]: check j<7 with arr[j]<18: arr[2,3,4,5]qualify (not 101) β best is dp[5]=3 β dp[7]=4 ([2,5,7,18])
Answer: max(dp) = 4
O(n log n) APPROACH (patience sorting): maintain `tails[]` = smallest possible
tail value for an increasing subsequence of each length so far.
10: tails=[10]
9: 9<10, replace β tails=[9]
2: 2<9, replace β tails=[2]
5: 5>2, append β tails=[2,5]
3: 3 fits between 2 and 5 β replace 5 β tails=[2,3]
7: 7>3, append β tails=[2,3,7]
101: append β tails=[2,3,7,101]
18: 18<101, replace 101 β tails=[2,3,7,18]
Final tails length = 4 β the ANSWER (length), though tails itself is NOT
necessarily a valid subsequence of the original array β it's a bookkeeping
structure, not the actual answer sequence.
(c) Coin Change (minimum coins) β coins {1, 3, 4}, target = 6
STATE: dp[a] = minimum number of coins summing to exactly amount a.
dp[0] = 0 (base case: 0 coins for amount 0)
dp[1]: try each coin β€ 1: coin=1 β dp[1] = dp[0]+1 = 1
dp[2]: coin=1 β dp[2] = dp[1]+1 = 2
dp[3]: coin=1 β dp[2]+1=3; coin=3 β dp[0]+1=1 β BEST = 1
dp[4]: coin=1 β dp[3]+1=2; coin=3 β dp[1]+1=2; coin=4 β dp[0]+1=1 β BEST = 1
dp[5]: coin=1 β dp[4]+1=2; coin=3 β dp[2]+1=3; coin=4 β dp[1]+1=2 β BEST = 2
dp[6]: coin=1 β dp[5]+1=3; coin=3 β dp[3]+1=2; coin=4 β dp[2]+1=3 β BEST = 2 (3+3)
Answer: dp[6] = 2 coins (using two 3-coins) β correctly finds the optimum,
UNLIKE the greedy approach from Chapter 10, which would have grabbed a 4
first and then struggled (4+1+1 = 3 coins, worse than DP's answer of 2).
4. Complexity Analysis
LCS: O(nΒ·m) time and space, where n, m are the two sequence lengths β directly analogous to 0/1 Knapsackβs O(nΒ·W) table, since both are 2D DP over a pair of βhow much of sequence/resource A and B have I consideredβ parameters.
LIS:
- O(nΒ²) DP approach: for each of the n positions, scan all previous positions β O(n) work per position, O(nΒ²) total.
- O(n log n) patience sorting approach: for each of the n elements, a binary search (Chapter 1) into the
tailsarray β O(log n) per element, O(n log n) total. This is a genuinely different (and better) algorithm achieving the same result, not just an optimization of the same DP.
Coin Change: O(amount Γ number of denominations) β for each of the amount+1 states, try each of the k coin denominations β O(1) work per (state, coin) pair.
Why these complexities hold: in every case, the complexity is (number of distinct DP states) Γ (cost to compute each stateβs transition) β the same general formula from Chapter 12, applied to each problemβs specific state space and transition cost.
5. Advantages
- These three problem shapes (2D sequence alignment, 1D subsequence tracking, unbounded resource combination) cover an enormous fraction of DP problems seen in interviews and real applications β recognizing βthis is LCS-shapedβ or βthis is Coin-Change-shapedβ is a massive practical shortcut.
- LISβs O(n log n) solution demonstrates that a DP-shaped problem doesnβt always need a DP-table solution β sometimes a cleverer non-DP algorithm (patience sorting) solves the same problem faster.
- Coin Change concretely demonstrates DP correctly solving a problem where greedy (Chapter 10) provably fails β a valuable, memorable illustration of the greedy-vs-DP distinction.
6. Limitations
- 2D DP problems (like LCS) cost O(nΒ·m) space in their naive form β can be optimized to O(min(n,m)) using the same βonly need the previous rowβ rolling technique from Chapter 12βs Knapsack space optimization, but this sacrifices the ability to reconstruct the actual sequence (only the length remains recoverable).
- LISβs O(n log n) approach, while faster, is less intuitive and doesnβt directly generalize as easily to variants (e.g., βcount the number of longest increasing subsequencesβ is far more natural with the O(nΒ²) DP version).
- Coin Changeβs DP assumes non-negative integer amounts and denominations β doesnβt directly extend to real-valued or negative-allowed variants without modification.
7. Real-World Applications
- LCS: the Unix
diffutility and Gitβs file-comparison features are built on LCS-family algorithms; DNA/protein sequence alignment in bioinformatics (with scoring-matrix variants like Needleman-Wunsch) is directly LCS-shaped. - LIS: stock trend analysis (longest period of increasing prices), patience sortingβs namesake card game, and scheduling problems involving compatible/ordered task sequences.
- Coin Change: currency/change-making systems, and more broadly, any βminimum number of resources to reach exactly a target using repeatable unit choicesβ problem (e.g., minimum number of standard package sizes to ship an exact weight).
- Version Control: merge algorithms and diff visualization tools rely on LCS-based sequence alignment.
- Natural Language Processing: sequence alignment techniques (related to LCS) appear in spell-checking and machine translation evaluation metrics (e.g., BLEU score calculations use related sequence-matching ideas).
- Compilers: some code-diffing and refactoring-detection tools use LCS-style algorithms to identify moved/modified code blocks.
8. C++ Implementation
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <climits>
// ---------- LONGEST COMMON SUBSEQUENCE ----------
// O(n*m) time and space.
int longestCommonSubsequence(const std::string& s1, const std::string& s2) {
int n = s1.size(), m = s2.size();
std::vector<std::vector<int>> dp(n + 1, std::vector<int>(m + 1, 0));
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (s1[i - 1] == s2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1; // characters match β extend the diagonal
} else {
dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]); // skip one char from either string
}
}
}
return dp[n][m];
}
// ---------- LONGEST INCREASING SUBSEQUENCE ----------
// O(n^2) DP approach.
int lengthOfLISQuadratic(const std::vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
std::vector<int> dp(n, 1); // dp[i] = length of LIS ending exactly at index i
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[j] < nums[i]) {
dp[i] = std::max(dp[i], dp[j] + 1);
}
}
}
return *std::max_element(dp.begin(), dp.end());
}
// O(n log n) patience-sorting approach.
int lengthOfLISOptimal(const std::vector<int>& nums) {
std::vector<int> tails; // tails[k] = smallest possible tail value for an increasing subsequence of length k+1
for (int num : nums) {
// Binary search (Chapter 1's lowerBound logic) for the first tail >= num.
auto it = std::lower_bound(tails.begin(), tails.end(), num);
if (it == tails.end()) {
tails.push_back(num); // num extends the longest subsequence so far
} else {
*it = num; // num gives a smaller/equal tail for this length β improves future extensibility
}
}
return static_cast<int>(tails.size());
}
// ---------- COIN CHANGE (minimum coins) ----------
// O(amount * coins.size()) time, O(amount) space.
int coinChange(const std::vector<int>& coins, int amount) {
std::vector<int> dp(amount + 1, INT_MAX);
dp[0] = 0;
for (int a = 1; a <= amount; ++a) {
for (int coin : coins) {
if (coin <= a && dp[a - coin] != INT_MAX) {
dp[a] = std::min(dp[a], dp[a - coin] + 1);
}
}
}
return dp[amount] == INT_MAX ? -1 : dp[amount]; // -1 signals "no valid combination"
}
// Example usage
int main() {
std::cout << "LCS(\"ABCBDAB\", \"BDCABA\"): "
<< longestCommonSubsequence("ABCBDAB", "BDCABA") << "\n"; // 4
std::vector<int> arr = {10, 9, 2, 5, 3, 7, 101, 18};
std::cout << "LIS quadratic: " << lengthOfLISQuadratic(arr) << "\n"; // 4
std::cout << "LIS optimal: " << lengthOfLISOptimal(arr) << "\n"; // 4
std::vector<int> coins = {1, 3, 4};
std::cout << "Coin Change (target=6): " << coinChange(coins, 6) << "\n"; // 2
return 0;
}
9. Code Walkthrough
longestCommonSubsequenceβs diagonal-extend vs. skip logic: directly implements section 3(a)βs recurrence β a character match extendsdp[i-1][j-1]diagonally by 1; a mismatch takes the better of skipping a character from either string, exactly mirroring 0/1 Knapsackβs βtake or skipβ structure from Chapter 12.lengthOfLISQuadraticβs nested loop: for each positioni, scans every earlier positionj, checking ifnums[j] < nums[i](a valid extension point) β this direct translation of the recursive definition (βwhatβs the best increasing subsequence ending here, considering every possible predecessorβ) is why it costs O(nΒ²).lengthOfLISOptimalβsstd::lower_bound: This is a direct reuse of Chapter 1βs Binary Search βtailsis always maintained in sorted order (a fact worth proving to yourself, though itβs not immediately obvious), so binary-searching it for the insertion point of each new number is valid and correct.- Why replacing a tail value (rather than just appending) is correct: finding a smaller possible tail value for a given subsequence length doesnβt shorten that subsequence β it just makes it more likely that future numbers can extend it, since a smaller tail is easier to exceed. This is the non-obvious insight that makes patience sorting work.
coinChangeβsdp[a-coin] != INT_MAXguard: prevents attempting to extend from an amount thatβs provably unreachable (still at the sentinelINT_MAX) β without this check,dp[a-coin]+1could silently wrap around or produce a nonsensical result due to integer overflow onINT_MAX + 1.
Common mistakes to watch for here:
- In LCS, forgetting the β1-indexed dp table vs. 0-indexed stringsβ offset, leading to off-by-one string-indexing errors.
- Assuming
tailsin the O(n log n) LIS approach directly represents a valid increasing subsequence of the original array β it does not; only its length is the meaningful output. - Forgetting the
INT_MAXguard in Coin Change, risking overflow or an incorrect βreachableβ determination for genuinely unreachable amounts. - Confusing 0/1 Knapsackβs βeach item onceβ constraint with Coin Changeβs βeach coin unlimited timesβ constraint β this single difference changes the loop structure (Coin Change can reuse the same rowβs already-updated values within a single pass, since a coin can be used again immediately).
10. Dry Run
coinChange({1,3,4}, target=6), already traced in full in section 3(c), arriving at dp[6]=2 via two uses of the 3-coin. Cross-check against the greedy failure from Chapter 10: greedy would grab the largest fitting coin first β 4 β leaving 2, which then needs 1+1 (two more coins), totaling 3 coins overall. DP correctly finds the better 2-coin solution (3+3) by considering all possibilities systematically rather than committing irrevocably to the first βbiggest fitβ choice.
11. Complexity Table
| Problem | Time | Space (naive) | Space (optimized) |
|---|---|---|---|
| LCS | O(nΒ·m) | O(nΒ·m) | O(min(n,m)) β length only, loses reconstruction ability |
| LIS (DP) | O(nΒ²) | O(n) | β |
| LIS (patience sorting) | O(n log n) | O(n) | β |
| Coin Change (min coins) | O(amount Β· k) | O(amount) | β |
Every entry explained: LCS and Coin Change follow the same βstates Γ transition costβ formula from Chapter 12. LIS is the interesting case in this chapter: two genuinely different algorithms solve the same problem at different complexities β the O(nΒ²) version directly mirrors the natural recursive definition, while the O(n log n) version replaces the DP table entirely with a cleverer greedy-plus-binary-search structure, illustrating that βthis problem looks DP-shapedβ doesnβt always mean βthe DP-table approach is the fastest available solution.β
12. Common Mistakes
- Off-by-one indexing errors in LCSβs 2D table β extremely common given the 1-indexed-table-vs-0-indexed-string mismatch.
- Misunderstanding what the
tailsarray represents in the O(n log n) LIS approach β it is NOT the actual longest increasing subsequence, only a bookkeeping structure whose length happens to equal the answer. - Applying 0/1 Knapsackβs loop structure to Coin Change (or vice versa) β the βeach item onceβ vs. βeach coin unlimitedβ distinction changes correct loop nesting/ordering, and mixing them up silently produces wrong answers for one variant or the other.
- Forgetting the unreachable-amount guard in Coin Change, risking overflow-related bugs.
- Assuming greedy would work for Coin Change without checking whether the denomination system is canonical (directly connects back to Chapter 10βs central lesson).
13. Interview Questions
Conceptual:
- Explain the LCS recurrence and why a character match forces a diagonal move in the DP table.
- Why does the O(n log n) LIS algorithmβs
tailsarray not represent an actual valid subsequence? - Why does Coin Change need DP rather than greedy, using the {1,3,4} target=6 counterexample?
- How does Coin Changeβs βunboundedβ (reuse allowed) nature change the DP loop structure compared to 0/1 Knapsackβs βboundedβ (use once) nature?
- How would you reconstruct the actual LCS string, not just its length, from the DP table?
Coding:
- Longest Common Subsequence β compute both length and the actual subsequence.
- Longest Increasing Subsequence β implement both O(nΒ²) and O(n log n) versions.
- Coin Change (minimum coins) and Coin Change II (count the number of ways β a related but distinct counting variant).
- Edit Distance (LeetCode 72) β an LCS-family variant with three operations (insert/delete/replace) instead of two.
- Longest Common Substring β a close relative of LCS requiring contiguous matching (subtly different DP transition).
- Russian Doll Envelopes (LeetCode 354) β a 2D LIS variant.
Follow-ups / interviewer traps:
- βCan you reduce LCSβs space to O(min(n,m))?β (expects the rolling-row technique, same as Knapsack, but flagging that reconstruction becomes impossible without extra bookkeeping)
- βCoin Change II counts the number of ways β how does the loop order differ from minimum-coins Coin Change, and why?β (tests deep understanding of unbounded-knapsack loop ordering: counting combinations requires iterating coins in the OUTER loop to avoid counting the same combination in different orders as distinct)
- βYour LIS solution β can you extend it to also return the actual subsequence, not just its length?β (tests whether the candidate over-relies on the
tailsarray without understanding its limitations, expects auxiliary parent-pointer tracking instead)
14. Practice Problems
Easy
- Longest Common Subsequence (LeetCode 1143)
Medium
- Longest Increasing Subsequence (LeetCode 300)
- Coin Change (LeetCode 322)
- Coin Change II (LeetCode 518)
- Delete Operation for Two Strings (LeetCode 583) β an LCS variant
- Maximum Length of Repeated Subarray (LeetCode 718) β Longest Common Substring variant
Hard
- Edit Distance (LeetCode 72)
- Longest Increasing Path in a Matrix (LeetCode 329) β LIS generalized to 2D with DFS+memoization
- Russian Doll Envelopes (LeetCode 354)
- Distinct Subsequences (LeetCode 115) β an LCS-family counting variant
Also recommended: solve the same LCS/LIS/Coin-Change-shaped problem using both the βobviousβ O(nΒ²)-or-worse approach and any faster known alternative β directly experiencing the speedup builds durable intuition for recognizing these shapes in novel problems.
15. Summary
Key takeaways:
- LCS, LIS, and Coin Change are three of the most reusable DP shapes in all of algorithmic problem-solving β an enormous fraction of βnovel-lookingβ DP interview problems are secretly one of these three in disguise.
- LIS uniquely demonstrates that a DP-shaped problem can sometimes be solved faster by an entirely different algorithmic idea (patience sorting + binary search) rather than the direct DP table.
- Coin Change is the definitive, concrete illustration of why Greedy (Chapter 10) cannot be trusted without proof β the exact same {1,3,4}-denomination counterexample recurs throughout this guide as a reminder.
Complexity recap:
| Time | Space | |
|---|---|---|
| LCS | O(nΒ·m) | O(nΒ·m), or O(min(n,m)) optimized |
| LIS | O(nΒ²) or O(n log n) | O(n) |
| Coin Change | O(amount Β· k) | O(amount) |
Decision guide: Recognize LCS-shaped problems by βcomparing two sequences, allowing skips in either.β Recognize LIS-shaped problems by βfinding structure within one sequence based on an ordering relationship.β Recognize Coin-Change-shaped problems by βcombining repeatable units to hit an exact target.β Once youβve correctly identified the shape, the specific transition and complexity analysis for that shape typically follows directly from the template in this chapter.
Next chapter: 14_graph_algorithms.md β connecting back to and extending the Data Structures guideβs Graphs chapters (Ch. 11-14) with additional algorithmic techniques (Floyd-Warshall, cycle detection variants, and more).
Chapter 14: Graph Algorithms
Study time: ~6-7 hours | Prerequisite: BFS/DFS, Dijkstraβs, MST, Topological Sort (Data Structures guide, Ch. 11-14) | Difficulty: Intermediate-Advanced
1. Introduction
Definition: This chapter completes the graph algorithm toolkit started in the Data Structures guide (Chapters 11-14 there cover representation, BFS, DFS, Topological Sort, MST via Kruskalβs/Primβs, and Shortest Path via Dijkstraβs/Bellman-Fordβs). Here we add Floyd-Warshall (all-pairs shortest path) and a systematic treatment of cycle detection across both directed and undirected graphs β the remaining pieces needed for a complete graph-algorithms picture.
Purpose: Dijkstraβs and Bellman-Fordβs (already covered) answer βshortest path from one source to everywhereβ β but many real problems need βshortest path between every pair of verticesβ simultaneously, which calls for a fundamentally different algorithm shape. Cycle detection, meanwhile, is a recurring sub-problem embedded inside many other graph algorithms (Topological Sortβs correctness depends on it, deadlock detection needs it directly), so it deserves its own systematic treatment.
Problem solved: βWhatβs the shortest path between every pair of vertices in a graph?β (Floyd-Warshall), and βdoes this graph contain a cycle, and if so, can I find it?β (cycle detection, with different techniques for directed vs. undirected graphs).
2. Intuition
Floyd-Warshallβs core insight: instead of thinking βwhatβs the shortest path from A to B,β think βwhatβs the shortest path from A to B, allowed to pass through only vertices {1, 2, β¦, k}?β β and build up the answer by incrementally allowing one more βintermediate vertexβ at a time. If allowing vertex k as a new intermediate stop ever creates a shorter path than what was known before (dist[i][k] + dist[k][j] < dist[i][j]), update it. After considering all n vertices as potential intermediates, every pairβs shortest path is guaranteed correct β this is dynamic programming applied directly to a graph problem, with the βstateβ being (source, destination, allowed intermediate vertices so far).
Cycle detectionβs core insight differs by graph type:
- Undirected graphs: during a DFS, if you reach an already-visited vertex that is not the immediate parent you just came from, youβve found a cycle β the βdonβt count the edge you just came fromβ exception is essential, since in an undirected graph, every edge naturally looks like it goes βbackβ to where you came from.
- Directed graphs: a back-edge to any ancestor still on the current DFS path (not just the immediate parent) indicates a cycle β this requires the three-state (unvisited/in-progress/finished) tracking introduced for Topological Sort in the Data Structures guide, since a directed graph can have an edge back to a vertex visited via a completely different branch (thatβs fine, no cycle) versus back to a vertex still actively on the current path (thatβs a genuine cycle).
3. Step-by-Step Working
(a) Floyd-Warshall β all-pairs shortest path
Graph (directed, weighted), 4 vertices A=0,B=1,C=2,D=3:
AβB(3), AβC(8), AβD(-4), BβD(1), BβA(4), CβB(7), DβC(6), DβA(2)
Initialize dist[i][j] = direct edge weight (or infinity if no edge, 0 if i==j):
A B C D
A [ 0, 3, 8, -4]
B [ 4, 0, inf, 1]
C [ inf, 7, 0, inf]
D [ 2, inf, 6, 0]
ITERATION k=0 (allow A as intermediate): check if dist[i][A]+dist[A][j] < dist[i][j] for all i,j.
e.g., dist[B][A]+dist[A][C] = 4+8=12, current dist[B][C]=inf β UPDATE to 12
e.g., dist[C][A]... dist[C][A] is inf, skip (no path through A helps here)
... (continue for all pairs)
ITERATION k=1 (allow B as intermediate): check dist[i][B]+dist[B][j] < dist[i][j]
e.g., dist[A][B]+dist[B][D] = 3+1=4, current dist[A][D]=-4 β NO improvement (4 > -4)
e.g., dist[D][B]...
ITERATION k=2 (allow C as intermediate): similar checks...
ITERATION k=3 (allow D as intermediate):
e.g., dist[A][D]+dist[D][C] = -4+6=2, current dist[A][C]=8 β UPDATE to 2!
e.g., dist[B][D]+dist[D][A] = 1+2=3, current dist[B][A]=4 β UPDATE to 3!
e.g., dist[B][D]+dist[D][C] = 1+6=7, current dist[B][C]=12 (from k=0) β UPDATE to 7!
Final dist[][] gives the shortest path between EVERY pair, having considered
routing through every possible intermediate vertex.
(b) Cycle Detection in an Undirected Graph
Graph: 0-1, 1-2, 2-0 (a triangle β contains a cycle)
DFS from 0, tracking parent:
visit 0 (parent=-1). Neighbor 1: not visited, recurse (parent=0).
visit 1 (parent=0). Neighbor 0: visited, but 0 IS the parent β not a cycle, skip.
Neighbor 2: not visited, recurse (parent=1).
visit 2 (parent=1). Neighbor 0: visited, and 0 is NOT the parent (parent is 1) β CYCLE DETECTED!
Neighbor 1: visited, but 1 IS the parent β not a cycle, skip.
Result: cycle found (0-1-2-0).
(c) Cycle Detection in a Directed Graph
Graph: 0β1, 1β2, 2β0 (a directed cycle)
DFS with 3-state tracking (0=unvisited, 1=in-progress, 2=finished):
visit 0, state[0]=1 (in-progress). Neighbor 1: unvisited, recurse.
visit 1, state[1]=1. Neighbor 2: unvisited, recurse.
visit 2, state[2]=1. Neighbor 0: state[0]=1 (IN-PROGRESS, meaning it's an
ancestor still on the current path) β CYCLE DETECTED (a back-edge to an
active ancestor)!
Contrast with a DAG like 0β1, 0β2, 1β3, 2β3 (no cycle, but 3 is reached via
TWO different paths): when DFS reaches 3 via the 0β1β3 path and marks it
FINISHED (state=2), the later arrival via 0β2β3 sees state[3]=2 (finished,
NOT in-progress) β correctly recognized as NOT a cycle, just a convergence.
4. Complexity Analysis
Floyd-Warshall: O(VΒ³) time, O(VΒ²) space. Three nested loops (choice of intermediate vertex k, source i, destination j), each O(1) work inside β VΓVΓV = O(VΒ³). Space is O(VΒ²) for the distance matrix itself (can be done in-place, updating the same matrix across iterations, since each dist[i][j] update only ever needs values from the current iterationβs matrix state, not a separate βprevious iterationβ copy β a subtle but important correctness detail proven in the algorithmβs original derivation).
Why O(VΒ³) is actually good for the all-pairs problem: running Dijkstraβs from every single vertex would cost O(V Β· E log V) β for a dense graph where E β VΒ², thatβs O(VΒ³ log V), worse than Floyd-Warshallβs clean O(VΒ³), and Floyd-Warshall additionally handles negative edges correctly (though not negative cycles, which it can detect but not βsolve aroundβ), which per-vertex Dijkstraβs cannot.
Cycle Detection (either type): O(V + E) β a single DFS traversal, with O(1) extra bookkeeping per vertex (a parent reference, or a 3-state marker) β identical complexity to plain DFS itself, since cycle detection adds no additional asymptotic cost, only a constant-factor bookkeeping overhead.
5. Advantages
- Floyd-Warshall answers ALL-PAIRS shortest path in one clean, simple-to-implement algorithm β no repeated single-source calls needed, and it naturally handles negative edge weights (unlike Dijkstraβs).
- Cycle detection techniques are lightweight (O(V+E), the same as plain traversal) and form an essential building block embedded inside many other algorithms (Topological Sort, deadlock detection, dependency validation).
- Floyd-Warshallβs triple-nested-loop structure is remarkably simple to implement correctly compared to its conceptual power β a rare case where an elegant algorithm is also genuinely easy to code.
6. Limitations
- Floyd-Warshallβs O(VΒ³) becomes impractical for very large graphs (tens of thousands of vertices or more) β itβs specifically suited to all-pairs queries on moderately-sized graphs, not a substitute for single-source algorithms when only one sourceβs distances are actually needed.
- Floyd-Warshall can detect a negative cycle (if any
dist[i][i]becomes negative after all iterations) but cannot produce a meaningful βshortest pathβ in the presence of one β shortest paths are undefined when negative cycles are reachable, since you could loop forever accumulating negative cost. - Cycle detectionβs specific technique (parent-tracking vs. 3-state) is graph-type-dependent β applying the undirected technique to a directed graph (or vice versa) produces incorrect results, since the two graph types have fundamentally different notions of what a βback edgeβ means.
7. Real-World Applications
- Networking: precomputing all-pairs shortest paths (or path costs) for network routing tables, when the network is small/stable enough that full recomputation is affordable.
- Transitive Closure Computation: Floyd-Warshallβs structure directly generalizes to computing βis vertex i reachable from vertex j at allβ (a boolean variant) β used in database query optimization and static analysis tools.
- Compilers: circular dependency detection (e.g., circular imports/includes) is a direct directed-cycle-detection application.
- Operating Systems: deadlock detection (a cycle in a βprocess waits for resource held by processβ graph) is a direct directed-cycle-detection application, and is genuinely used in real database/OS deadlock detectors.
- Build Systems: validating that a dependency graph is truly acyclic (before even attempting Topological Sort) is directly cycle detection.
- Finance: all-pairs shortest path (with edge weights as negative log-exchange-rates) is a classic technique for detecting arbitrage opportunities across an entire currency network simultaneously, extending the single-source Bellman-Ford arbitrage detection mentioned in the Data Structures guide.
- Game Development: precomputed all-pairs distances between key locations on a small, static game map for instant pathfinding queries at runtime.
8. C++ Implementation
#include <iostream>
#include <vector>
#include <limits>
const int INF = std::numeric_limits<int>::max() / 2; // avoid overflow when summing two INFs
// Floyd-Warshall: all-pairs shortest path. O(V^3) time, O(V^2) space.
// dist[i][j] should be pre-initialized to the direct edge weight, INF if no edge, 0 if i==j.
void floydWarshall(std::vector<std::vector<int>>& dist) {
int V = static_cast<int>(dist.size());
for (int k = 0; k < V; ++k) { // try allowing vertex k as an intermediate stop
for (int i = 0; i < V; ++i) {
for (int j = 0; j < V; ++j) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j]; // routing through k is shorter β update
}
}
}
}
// After all iterations: if any dist[i][i] < 0, a negative cycle exists reachable through i.
}
// Cycle Detection in an UNDIRECTED graph. O(V+E).
bool hasCycleUndirectedHelper(int u, int parent, std::vector<bool>& visited,
const std::vector<std::vector<int>>& adjList) {
visited[u] = true;
for (int neighbor : adjList[u]) {
if (!visited[neighbor]) {
if (hasCycleUndirectedHelper(neighbor, u, visited, adjList)) return true;
} else if (neighbor != parent) {
return true; // visited AND not the parent we just came from β a genuine cycle
}
}
return false;
}
bool hasCycleUndirected(int V, const std::vector<std::vector<int>>& adjList) {
std::vector<bool> visited(V, false);
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
if (hasCycleUndirectedHelper(v, -1, visited, adjList)) return true;
}
}
return false;
}
// Cycle Detection in a DIRECTED graph. O(V+E). Reuses the 3-state technique from Topological Sort.
bool hasCycleDirectedHelper(int u, std::vector<int>& state, const std::vector<std::vector<int>>& adjList) {
state[u] = 1; // in-progress (on the current DFS path)
for (int neighbor : adjList[u]) {
if (state[neighbor] == 1) return true; // back-edge to an ACTIVE ancestor β cycle
if (state[neighbor] == 0 && hasCycleDirectedHelper(neighbor, state, adjList)) return true;
}
state[u] = 2; // finished
return false;
}
bool hasCycleDirected(int V, const std::vector<std::vector<int>>& adjList) {
std::vector<int> state(V, 0);
for (int v = 0; v < V; ++v) {
if (state[v] == 0) {
if (hasCycleDirectedHelper(v, state, adjList)) return true;
}
}
return false;
}
// Example usage
int main() {
// Floyd-Warshall example (4 vertices, from section 3(a))
int V = 4;
std::vector<std::vector<int>> dist(V, std::vector<int>(V, INF));
for (int i = 0; i < V; ++i) dist[i][i] = 0;
dist[0][1] = 3; dist[0][2] = 8; dist[0][3] = -4;
dist[1][3] = 1; dist[1][0] = 4;
dist[2][1] = 7;
dist[3][2] = 6; dist[3][0] = 2;
floydWarshall(dist);
std::cout << "All-pairs shortest distances:\n";
for (auto& row : dist) {
for (int d : row) std::cout << (d >= INF ? -1 : d) << " ";
std::cout << "\n";
}
// Undirected cycle detection
std::vector<std::vector<int>> undirectedAdj(3);
undirectedAdj[0] = {1, 2}; undirectedAdj[1] = {0, 2}; undirectedAdj[2] = {0, 1};
std::cout << "Undirected graph has cycle? " << hasCycleUndirected(3, undirectedAdj) << "\n"; // 1 (true)
// Directed cycle detection
std::vector<std::vector<int>> directedAdj(3);
directedAdj[0] = {1}; directedAdj[1] = {2}; directedAdj[2] = {0};
std::cout << "Directed graph has cycle? " << hasCycleDirected(3, directedAdj) << "\n"; // 1 (true)
return 0;
}
9. Code Walkthrough
floydWarshallβs triple loop order (koutermost): This ordering is not arbitrary βkMUST be the outermost loop, because iterationkrepresents βshortest paths allowed to use intermediates {0,β¦,k},β and each iterationβs correctness depends on the previous iteration (k-1) having already been fully completed for ALL(i,j)pairs beforekis considered as a new intermediate. Swapping the loop order breaks this dependency and produces incorrect results.INF/2instead of the raw maximum int value: Adding twoINFvalues (dist[i][k] + dist[k][j]when neither path exists) could overflow if using the true maximum representable integer β dividing by 2 upfront leaves enough headroom for one addition without wrapping around.hasCycleUndirectedHelperβsneighbor != parentcheck: This is the critical distinction from directed cycle detection β in an undirected graph, the edge you just traversed to arrive at the current vertex will always appear as a βvisited neighborβ when you look back, and this is expected, not a cycle; only a visited neighbor that ISNβT your immediate parent indicates a genuine additional cycle-forming edge.hasCycleDirectedHelperβs 3-state check (state[neighbor] == 1): This is exactly the Topological Sort cycle-detection logic from the Data Structures guide, reused verbatim β a back-edge to a vertex still marked βin-progressβ (actively on the current recursion path, state 1) is a genuine cycle; a back-edge to a βfinishedβ vertex (state 2) is just a harmless convergence of two different paths onto the same vertex, common in any DAG with multiple valid routes to the same node.- Both cycle-detection functions looping over all vertices as potential start points: neither assumes the graph is connected β disconnected components are each given their own DFS starting point, ensuring the whole graph (not just one component) is checked.
Common mistakes to watch for here:
- Placing Floyd-Warshallβs
kloop anywhere other than outermost, silently producing incorrect shortest-path results. - Using the undirected βparent-trackingβ cycle detection technique on a directed graph (or vice versa) β these are genuinely different algorithms suited to genuinely different graph semantics, not interchangeable.
- Forgetting to check all vertices as potential DFS starting points in either cycle-detection function, missing cycles hidden in a disconnected component.
10. Dry Run
Floyd-Warshall, k=3 (vertex D) iteration, continuing from section 3(a)βs setup:
| Check | dist[i][k]+dist[k][j] | Current dist[i][j] | Update? |
|---|---|---|---|
| i=A,j=C via D | dist[A][D]+dist[D][C] = -4+6 = 2 | 8 | YES β dist[A][C]=2 |
| i=B,j=A via D | dist[B][D]+dist[D][A] = 1+2 = 3 | 4 | YES β dist[B][A]=3 |
| i=B,j=C via D | dist[B][D]+dist[D][C] = 1+6 = 7 | 12 (updated at k=0) | YES β dist[B][C]=7 |
These three updates match section 3(a)βs trace exactly, confirming the final all-pairs distance matrix correctly reflects the benefit of routing through D as an intermediate stop. β
11. Complexity Table
| Algorithm | Time | Space |
|---|---|---|
| Floyd-Warshall | O(VΒ³) | O(VΒ²) |
| Cycle Detection (undirected or directed) | O(V+E) | O(V) |
Every entry explained: Floyd-Warshallβs O(VΒ³) comes directly from its triple-nested-loop structure, with no shortcuts possible in the general case (this is provably close to optimal for dense graphs, though sparse-graph-specific algorithms can sometimes do better). Cycle detectionβs O(V+E) is identical to plain DFS, since the extra bookkeeping (a parent reference or a 3-state array) adds only O(1) work per vertex/edge examined.
12. Common Mistakes
- Wrong loop order in Floyd-Warshall β
kmust be outermost; this is the single most common implementation bug for this algorithm. - Integer overflow from adding two INF sentinel values β always leave headroom (e.g.,
INF/2) rather than using the raw maximum representable value. - Confusing undirected and directed cycle-detection techniques β applying the wrong one to the wrong graph type produces silently incorrect results (a directed graph checked with the βparent-onlyβ undirected technique can miss legitimate cycles that donβt involve the immediate parent).
- Not checking all vertices as DFS starting points, missing cycles in disconnected components.
- Assuming Floyd-Warshall handles negative cycles gracefully β it can detect one (a negative value appearing on the diagonal), but the resulting βshortest pathsβ involving that cycle are meaningless, since no finite shortest path exists when a negative cycle is reachable.
13. Interview Questions
Conceptual:
- Why must Floyd-Warshallβs intermediate-vertex loop (
k) be the outermost of the three loops? - Compare running Dijkstraβs V times versus Floyd-Warshall for the all-pairs shortest path problem β when is each preferable?
- Explain why undirected and directed graphs need fundamentally different cycle-detection techniques.
- How does Floyd-Warshall detect a negative cycle, and why canβt it produce meaningful shortest paths once one exists?
- Why is a back-edge to a βfinishedβ vertex in directed-graph DFS NOT necessarily a cycle, while a back-edge to an βin-progressβ vertex always is?
Coding:
- Implement Floyd-Warshall and detect negative cycles.
- Implement cycle detection for both undirected and directed graphs.
- Course Schedule (LeetCode 207) β directed cycle detection applied directly.
- Redundant Connection (LeetCode 684) β undirected cycle detection, finding the specific edge that creates a cycle (naturally solved with DSU too β connecting back to the Data Structures guide).
- Find the City With the Smallest Number of Neighbors at a Threshold Distance (LeetCode 1334) β a direct Floyd-Warshall application.
Follow-ups / interviewer traps:
- βYour graph has up to 500 vertices β is Floyd-Warshall or repeated Dijkstraβs better here?β (tests recognizing that for moderate V, O(VΒ³) is fine, while for large V, repeated Dijkstraβs β or a smarter all-pairs approach β would be needed instead)
- βCan Floyd-Warshall detect WHICH cycle is negative, not just that one exists?β (tests deeper algorithmic thinking β requires additional bookkeeping/backtracking beyond the basic algorithm)
- βRedundant Connection β can you solve it with DSU instead of cycle-detection DFS? Which is more natural here?β (tests recognizing that DSUβs βare these already connected?β check is often a cleaner fit for this specific problem shape than a full DFS-based cycle check)
14. Practice Problems
Easy
- Find the Town Judge (LeetCode 997) β light graph/cycle-adjacent reasoning
Medium
- Course Schedule (LeetCode 207) / Course Schedule II (LeetCode 210)
- Redundant Connection (LeetCode 684)
- Find the City With the Smallest Number of Neighbors at a Threshold Distance (LeetCode 1334)
Hard
- Redundant Connection II (LeetCode 685) β the directed-graph variant, genuinely harder
- Minimum Cost to Make at Least One Valid Path in a Grid (mixed shortest-path/graph-modeling problem)
Also recommended: GeeksforGeeks βFloyd Warshall Algorithmβ and βDetect Cycle in a Graphβ practice sets; implement transitive closure (boolean reachability) as a Floyd-Warshall variant for additional practice with the pattern.
15. Summary
Key takeaways:
- Floyd-Warshall solves all-pairs shortest path in O(VΒ³) via dynamic programming over βwhich vertices are allowed as intermediatesβ β a fundamentally different algorithmic shape than the single-source algorithms (Dijkstraβs, Bellman-Fordβs) covered in the Data Structures guide.
- Cycle detection requires genuinely different techniques for undirected graphs (parent-tracking) versus directed graphs (3-state in-progress/finished tracking) β these are not interchangeable, and this distinction underlies Topological Sortβs own correctness check.
- Together with the Data Structures guideβs BFS/DFS/Dijkstraβs/Bellman-Fordβs/MST/Topological Sort, this chapter completes a comprehensive graph-algorithms toolkit covering traversal, shortest paths (single-source and all-pairs), minimum connectivity, ordering, and structural validation.
Complexity recap:
| Time | Space | |
|---|---|---|
| Floyd-Warshall | O(VΒ³) | O(VΒ²) |
| Cycle Detection | O(V+E) | O(V) |
Decision guide: Use Floyd-Warshall when you need shortest paths between EVERY pair of vertices and the graph is small/moderate in size (a few hundred to a few thousand vertices, depending on performance requirements). Use cycle detection whenever validating a dependency graph, checking for deadlock conditions, or as a building block before attempting Topological Sort. For single-source shortest paths, prefer Dijkstraβs/Bellman-Fordβs (Data Structures guide, Ch. 14) over running Floyd-Warshall and discarding unused rows.
Next chapter: 15_tree_algorithms.md
Chapter 15: Tree Algorithms
Study time: ~5-6 hours | Prerequisite: Binary Tree/BST (Data Structures guide, Ch. 7), Recursion | Difficulty: Intermediate
1. Introduction
Definition: This chapter covers the essential algorithmic techniques applied to trees, building on the Data Structures guideβs Binary Tree/BST/AVL chapters (which covered the structures themselves): the four traversal orders, the Lowest Common Ancestor (LCA) problem, and Tree Diameter β three of the most frequently-tested tree-algorithm patterns in interviews.
Purpose: To move from βI know what a tree is and how to insert/search/deleteβ (Data Structures guide) to βI can solve non-trivial algorithmic questions about a treeβs structure and relationships between its nodesβ β the kind of question interviewers ask once theyβve confirmed basic tree fluency.
Problem solved: Visiting tree nodes in a specific meaningful order (traversal), finding the deepest shared ancestor of two nodes (LCA β useful for βhow are these two things related in a hierarchyβ queries), and finding the longest path between any two nodes in a tree (Diameter β useful for βwhatβs the worst-case distance in this hierarchical structureβ queries).
2. Intuition
Traversals are simply βin what order do I visit a treeβs nodesβ β and the four standard orders (pre-order, in-order, post-order, level-order) each serve a different natural purpose: pre-order visits a node before its children (useful for copying/serializing a tree, since you can reconstruct it by processing parents before their children); in-order visits left-subtree, then node, then right-subtree (useful specifically for BSTs, since it produces sorted output β covered in the Data Structures guide); post-order visits children before the node itself (useful for safely deleting a tree, or for any computation that needs a nodeβs childrenβs results before computing the nodeβs own result β directly foreshadowing Tree Diameter below); level-order visits nodes level by level (useful for anything requiring breadth-first, βclosest firstβ processing, using a Queue exactly as BFS does on graphs).
LCAβs intuition: the lowest common ancestor of two nodes is the deepest node that has both as descendants (a node can be its own ancestor for this purpose). The key recursive insight: search both subtrees of the current node for the two targets; if one target is found in the left subtree and the other in the right subtree, the current node itself IS the LCA (itβs the point where their paths from the root diverge); if both are found in the same subtree, the LCA must be deeper within that subtree, so recurse further.
Tree Diameterβs intuition: the diameter (longest path between any two nodes, not necessarily through the root) at any given node can be computed as βthe height of its left subtree + the height of its right subtreeβ (the longest path that passes through this node) β and the overall answer is the maximum of this quantity across every node in the tree, not just the root. This is why computing diameter naturally pairs with a post-order traversal: you need each subtreeβs height already computed before you can evaluate whether the current node offers the best βleft height + right heightβ path.
3. Step-by-Step Working
(a) Four Traversals on this tree:
1
/ \
2 3
/ \
4 5
Pre-order (Node, Left, Right): 1, 2, 4, 5, 3
In-order (Left, Node, Right): 4, 2, 5, 1, 3
Post-order (Left, Right, Node): 4, 5, 2, 3, 1
Level-order (BFS, level by level): 1, 2, 3, 4, 5
(b) Lowest Common Ancestor β find LCA(4, 5) and LCA(4, 3) in the same tree
LCA(4, 5):
Start at 1. Search left subtree (rooted at 2) for {4,5}: found BOTH 4 and 5 there.
Search right subtree (rooted at 3): found NEITHER.
Since both targets are in the LEFT subtree only, recurse into node 2's subtree specifically.
At node 2: search left (4): found 4. search right (5): found 5.
Found ONE in each subtree of node 2 β node 2 IS the LCA.
Answer: LCA(4,5) = 2
LCA(4, 3):
Start at 1. Search left subtree (2): found 4 (not 3).
Search right subtree (3): found 3 (not 4).
Found ONE target in EACH subtree of node 1 β node 1 IS the LCA.
Answer: LCA(4,3) = 1
(c) Tree Diameter β find the longest path in this tree:
1
/ \
2 3
/ \
4 5
/
6
Post-order computation (compute height bottom-up, track best diameter seen so far):
Node 6 (leaf): height=1. No children, diameter candidate = 0.
Node 4: left child = 6 (height 1), no right child (height 0).
height(4) = 1 + max(1,0) = 2.
diameter candidate at node 4 = leftHeight + rightHeight = 1 + 0 = 1.
Node 5 (leaf): height=1. diameter candidate = 0.
Node 2: left child = 4 (height 2), right child = 5 (height 1).
height(2) = 1 + max(2,1) = 3.
diameter candidate at node 2 = 2 + 1 = 3. β path 6-4-2-5, length 3 edges
Node 3 (leaf): height=1. diameter candidate = 0.
Node 1: left child = 2 (height 3), right child = 3 (height 1).
height(1) = 1 + max(3,1) = 4.
diameter candidate at node 1 = 3 + 1 = 4. β path 6-4-2-1-3, length 4 edges β the OVERALL best
Final diameter = max(all candidates seen) = 4 (the path 6β4β2β1β3)
Critical insight: the overall diameter (4, through node 1) is NOT the same as the best candidate at just the root β node 2 had a candidate of 3, but the true maximum (4) only appears when comparing across ALL nodes, which is exactly why the algorithm must track a running βbest seen so farβ across the entire post-order traversal, not just return the rootβs own candidate.
4. Complexity Analysis
All four traversals: O(n) time, O(h) space (h = tree height, for the recursion call stack; O(n) for level-orderβs explicit queue, since a queue can hold an entire tree βlevel,β which in the worst case β a very wide, shallow tree β can be O(n) wide).
LCA (recursive, single query): O(n) time, O(h) space β in the worst case, the recursive search must visit every node once (if the targets are deep in different branches, or the tree is a single long chain), and the recursion stack depth equals the treeβs height.
Tree Diameter: O(n) time, O(h) space β a single post-order traversal, visiting every node exactly once, with O(1) work at each node (computing height and updating the running-best diameter) β this is why pairing βcompute heightβ and βcheck diameter candidateβ into a SINGLE traversal (rather than two separate passes) is the efficient approach; a naive βcompute diameter separately at every node by re-traversing its subtreesβ would cost O(nΒ²).
Why combining height-computation and diameter-checking into one pass matters: if you computed each nodeβs subtree height with a separate traversal call for every node (a natural but naive first attempt), youβd redundantly re-traverse the same subtrees over and over β O(n) work per node, times n nodes, giving O(nΒ²) total. Returning the height as part of the same recursive call that also updates the diameter candidate avoids this entirely, collapsing back to a single O(n) pass β an important, broadly-applicable lesson: whenever a tree recursion needs both βa value from belowβ and βa global answer,β try to compute both in the same traversal rather than two separate ones.
5. Advantages
- Traversals are simple, foundational building blocks reused throughout virtually every other tree algorithm (LCA and Diameter both build directly on post-order-style recursive thinking).
- LCAβs recursive approach is elegant and handles the general case (not just BSTs) in one clean O(n) pass, correctly identifying the exact divergence point of two nodesβ root-to-node paths.
- Tree Diameter demonstrates a broadly reusable pattern β combining a βbottom-up valueβ (height) with a βglobal running bestβ (diameter) in a single traversal β that generalizes to many other tree problems beyond diameter specifically.
6. Limitations
- The general LCA algorithm shown here is O(n) per query β for a workload with many repeated LCA queries on a static tree, preprocessing techniques (binary lifting, Euler tour + Sparse Table) can answer each query in O(log n) or even O(1) after O(n log n) preprocessing, at the cost of significantly more implementation complexity.
- BST-specific LCA can be solved more simply (and faster per query, O(h) rather than O(n)) by exploiting the BST ordering property directly β using the general tree algorithm on a BST specifically would be needlessly conservative.
- Tree Diameterβs approach, while efficient, requires careful handling of the βglobal bestβ variable across the recursion (commonly via a reference parameter or a class member) β a common source of subtle bugs for learners unfamiliar with this pattern.
7. Real-World Applications
- File Systems: directory traversal (listing all files, computing total sizes) is a direct application of tree traversal (typically post-order, so a directoryβs size can be computed after all its contents are known).
- Compilers: Abstract Syntax Tree (AST) traversal for code generation (typically post-order, generating code for sub-expressions before the operations that combine them) and static analysis.
- Organizational Charts / Hierarchies: LCA directly answers βwhatβs the lowest common manager of these two employees?β β a natural real-world framing of the exact algorithm.
- Version Control: finding the common ancestor commit of two branches (Gitβs merge-base computation) is conceptually an LCA problem over the commit history DAG (a generalization of tree LCA to DAGs).
- Network Topology: finding the point where two network paths converge (useful for routing/multicast tree construction) is an LCA-style computation.
- Phylogenetics (Biology): finding the most recent common ancestor species of two organisms in an evolutionary tree is a direct, literal application of the LCA algorithm.
- UI/DOM Trees: finding the common ancestor element of two DOM nodes (used internally by browsers for event bubbling/capturing logic) is an LCA computation.
8. C++ Implementation
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}
};
// ---------- TRAVERSALS ----------
void preOrder(TreeNode* node, std::vector<int>& result) {
if (!node) return;
result.push_back(node->val); // NODE first
preOrder(node->left, result);
preOrder(node->right, result);
}
void inOrder(TreeNode* node, std::vector<int>& result) {
if (!node) return;
inOrder(node->left, result);
result.push_back(node->val); // NODE in the middle
inOrder(node->right, result);
}
void postOrder(TreeNode* node, std::vector<int>& result) {
if (!node) return;
postOrder(node->left, result);
postOrder(node->right, result);
result.push_back(node->val); // NODE last
}
std::vector<int> levelOrder(TreeNode* root) {
std::vector<int> result;
if (!root) return result;
std::queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* curr = q.front(); q.pop();
result.push_back(curr->val);
if (curr->left) q.push(curr->left);
if (curr->right) q.push(curr->right);
}
return result;
}
// ---------- LOWEST COMMON ANCESTOR ----------
// O(n) per query. Works for any binary tree (not just BST).
TreeNode* lowestCommonAncestor(TreeNode* node, TreeNode* p, TreeNode* q) {
if (!node || node == p || node == q) return node; // found one of the targets, or hit a dead end
TreeNode* left = lowestCommonAncestor(node->left, p, q);
TreeNode* right = lowestCommonAncestor(node->right, p, q);
if (left && right) return node; // found one target in EACH subtree β this node is the LCA
return left ? left : right; // otherwise, propagate whichever side found something (or nullptr)
}
// ---------- TREE DIAMETER ----------
// O(n). Combines height-computation and diameter-tracking into a single post-order pass.
int diameterHelper(TreeNode* node, int& diameter) {
if (!node) return 0;
int leftHeight = diameterHelper(node->left, diameter);
int rightHeight = diameterHelper(node->right, diameter);
diameter = std::max(diameter, leftHeight + rightHeight); // update global best with THIS node's candidate
return 1 + std::max(leftHeight, rightHeight); // return height, for the PARENT's use
}
int treeDiameter(TreeNode* root) {
int diameter = 0;
diameterHelper(root, diameter);
return diameter;
}
// Example usage
int main() {
// 1
// / \
// 2 3
// / \
// 4 5
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
std::vector<int> pre, in, post;
preOrder(root, pre); inOrder(root, in); postOrder(root, post);
auto level = levelOrder(root);
auto print = [](const std::string& label, const std::vector<int>& v) {
std::cout << label << ": ";
for (int x : v) std::cout << x << " ";
std::cout << "\n";
};
print("Pre-order", pre); // 1 2 4 5 3
print("In-order", in); // 4 2 5 1 3
print("Post-order", post); // 4 5 2 3 1
print("Level-order", level); // 1 2 3 4 5
TreeNode* lca = lowestCommonAncestor(root, root->left->left, root->left->right);
std::cout << "LCA(4,5) = " << lca->val << "\n"; // 2
// Add node 6 under 4 for the diameter example
root->left->left->left = new TreeNode(6);
std::cout << "Tree Diameter = " << treeDiameter(root) << "\n"; // 4
return 0;
}
9. Code Walkthrough
- The three DFS-based traversals (
preOrder/inOrder/postOrder): all three share an identical recursive skeleton β the ONLY difference is whereresult.push_back(node->val)appears relative to the two recursive calls. This makes the three traversal orders trivially easy to remember once you see them side by side: node-first, node-middle, node-last. levelOrderβs queue-based approach: Directly mirrors BFS on a graph (Data Structures guide, Ch. 11) β a tree is, after all, just a special (acyclic, single-parent) graph, so the same Queue-based level-by-level exploration applies unchanged.lowestCommonAncestorβs base casenode == p || node == q: Returning the node itself the moment either target is found (rather than continuing to search deeper) is what correctly handles the case where one target is an ancestor of the other (e.g., LCA(2, 5) where 2 is 5βs direct parent) β the function returns 2 immediately upon reaching it, without needing to separately search for 5 further down.lowestCommonAncestorβsif (left && right) return node;: This is the exact moment the algorithm identifies the LCA β finding one target on each side means the current node is precisely where the two targetsβ paths from the root diverge.diameterHelperβs dual return/reference-parameter pattern: The functionreturns the height (for the parent call to use in its OWN height computation), while separately updatingdiameter(passed by reference) as a global running best across the entire traversal β this dual-purpose design is exactly the βcompute both a bottom-up value and a global answer in one passβ pattern flagged as broadly reusable in section 4.
Common mistakes to watch for here:
- Mixing up the three traversal ordersβ node-placement (a very easy slip when writing them quickly without care).
- In LCA, returning too early or too late relative to checking
node == p || node == q, causing incorrect results when one target is an ancestor of the other. - In Tree Diameter, forgetting that the diameter can be found at ANY node, not just the root β only checking the rootβs own left-height + right-height would miss diameters entirely contained within a subtree (as shown in section 3(c), where the true diameter passes through node 1, but a naive root-only check would have needed to correctly identify node 1 as involved β always compute and compare at every single node, not just the root).
10. Dry Run
treeDiameter on the 6-node tree from section 3(c), matching that sectionβs full trace exactly:
| Node | leftHeight | rightHeight | diameter candidate | height returned | Running max diameter |
|---|---|---|---|---|---|
| 6 | 0 | 0 | 0 | 1 | 0 |
| 4 | 1 (from 6) | 0 | 1 | 2 | 1 |
| 5 | 0 | 0 | 0 | 1 | 1 |
| 2 | 2 (from 4) | 1 (from 5) | 3 | 3 | 3 |
| 3 | 0 | 0 | 0 | 1 | 3 |
| 1 | 3 (from 2) | 1 (from 3) | 4 | 4 | 4 |
Final diameter = 4, confirmed matching section 3(c)βs manual derivation. β
11. Complexity Table
| Algorithm | Time | Space |
|---|---|---|
| Pre/In/Post-order Traversal | O(n) | O(h) recursion stack |
| Level-order Traversal | O(n) | O(n) worst case (wide tree, queue holds a full level) |
| LCA (general binary tree, single query) | O(n) | O(h) |
| LCA (BST-specific, single query) | O(h) | O(h) or O(1) iterative |
| Tree Diameter | O(n) | O(h) |
Every entry explained: All traversals and Tree Diameter visit every node exactly once, giving O(n) β the only variation is space, which depends on recursion depth (O(h)) versus the widest single level (O(n) for level-order in the worst case of a very wide, shallow tree). BST-specific LCA is faster (O(h) rather than O(n)) because the BST ordering property lets you immediately decide βgo left or rightβ at each step, exactly like BST search, rather than needing to search both subtrees as the general algorithm does.
12. Common Mistakes
- Confusing the three DFS traversal orders β always double check where the βvisit nodeβ step falls relative to the two recursive calls.
- Using the general O(n) LCA algorithm on a BST when the much faster O(h) BST-specific version (exploiting the ordering property) would suffice β a missed optimization opportunity, not incorrect, but worth recognizing.
- Computing Tree Diameter with a separate height-computation call at every node (rather than combining height and diameter-tracking into one pass) β silently degrades from O(n) to O(nΒ²).
- Checking diameter only at the root instead of at every node during the traversal β misses diameters that lie entirely within a subtree, not passing through the root.
- Forgetting that a node can be its own ancestor in the LCA definition β LCA(node, nodeβs descendant) should correctly return
nodeitself, not fail or search further.
13. Interview Questions
Conceptual:
- Explain the difference between the three DFS traversal orders and give a real use case for each.
- Why does LCAβs recursive algorithm correctly identify the divergence point of two nodesβ paths from the root?
- Why must Tree Diameterβs computation check every node, not just the root?
- How would you speed up LCA for a static tree with many repeated queries?
- How does BST-specific LCA differ from and improve upon the general binary tree LCA algorithm?
Coding:
- Implement all four traversals (iterative versions too, using an explicit stack for pre/in/post-order).
- Lowest Common Ancestor of a Binary Tree (LeetCode 236) and of a BST (LeetCode 235) β implement both, compare.
- Diameter of Binary Tree (LeetCode 543).
- Binary Tree Level Order Traversal (LeetCode 102) and its zigzag variant (LeetCode 103).
- Serialize and Deserialize a Binary Tree (uses pre-order traversal as its core mechanism β connects back to the Data Structures guideβs BST chapter).
- Path Sum problems β natural extensions of the post-order βcompute from childrenβ pattern.
Follow-ups / interviewer traps:
- βCan you find LCA without extra space, for a very deep tree?β (tests awareness of iterative traversal techniques, or Morris-traversal-style O(1)-space approaches for advanced variants)
- βYour tree has parent pointers available β does that change your LCA approach?β (yes β with parent pointers, LCA can be solved similarly to the linked-list-intersection problem, walking both paths to the root and finding where they converge)
- βDiameter of Binary Tree β what if edge weights arenβt uniform (weighted diameter)?β (tests generalizing the height-tracking pattern to weighted sums instead of simple edge counts)
14. Practice Problems
Easy
- Binary Tree Preorder/Inorder/Postorder Traversal (LeetCode 144/94/145)
- Binary Tree Level Order Traversal (LeetCode 102)
- Diameter of Binary Tree (LeetCode 543)
Medium
- Lowest Common Ancestor of a Binary Tree (LeetCode 236)
- Lowest Common Ancestor of a BST (LeetCode 235)
- Binary Tree Zigzag Level Order Traversal (LeetCode 103)
- Path Sum II (LeetCode 113)
Hard
- Binary Tree Maximum Path Sum (LeetCode 124) β a weighted generalization of the Diameter pattern
- Serialize and Deserialize Binary Tree (LeetCode 297)
- Vertical Order Traversal of a Binary Tree (LeetCode 987)
Also recommended: GeeksforGeeks βTree Traversalsβ and βLowest Common Ancestorβ practice sets; implement iterative (non-recursive, explicit-stack) versions of all three DFS traversals as a valuable exercise in understanding what recursion is doing βunder the hood.β
15. Summary
Key takeaways:
- The three DFS traversal orders (pre/in/post) differ only in WHEN the current node is visited relative to its children β a simple distinction with significant downstream implications for which problems each order naturally solves.
- LCAβs recursive elegance comes from recognizing that finding one target in each subtree of a node means that node IS the divergence point β the LCA.
- Tree Diameter demonstrates the powerful, broadly-reusable pattern of combining a βvalue needed by the parentβ (height) with a βglobal running bestβ (diameter) in a single traversal pass, avoiding redundant re-traversal.
Complexity recap:
| Time | Space | |
|---|---|---|
| Traversals | O(n) | O(h) or O(n) for level-order |
| LCA (general) | O(n) | O(h) |
| Tree Diameter | O(n) | O(h) |
Decision guide: Use pre-order for copying/serializing a tree top-down; in-order specifically for BSTs when you need sorted output; post-order whenever a computation needs childrenβs results before the parentβs (deletion, height/diameter-style aggregation); level-order whenever you need breadth-first, level-by-level processing. Use the general LCA algorithm for arbitrary binary trees; switch to the faster BST-specific version when you know the tree is a BST. Recognize Tree-Diameter-shaped problems by their βcombine a bottom-up value with a global best across all nodesβ structure β this same shape recurs in many other tree problems beyond diameter itself.
Next chapter: 16_string_algorithms.md β completing the guide by connecting to and extending the Data Structures guideβs String chapter (KMP, Z-Function, Rabin-Karp).
Chapter 16: String Algorithms (Capstone)
Study time: ~4-5 hours | Prerequisite: Data Structures guide Ch. 2 (KMP, Z-Function, Rabin-Karp) and Ch. 9 (Trie) | Difficulty: Intermediate This chapter completes the Algorithms Handbook β it connects the pattern-matching algorithms already built in the Data Structures guide into the broader algorithmic pattern-recognition framework this guide has developed.
1. Introduction
Definition: String Algorithms are techniques for efficiently searching, comparing, and analyzing sequences of characters. The core pattern-matching algorithms β KMP, the Z-Function, and Rabin-Karp β were already built in full depth in the Data Structures guideβs Chapter 2, alongside Trie in Chapter 9. This chapterβs job is different: to make sure you can recognize which technique a given string problem calls for, to formalize Rolling Hash as a standalone reusable concept (itβs the engine inside Rabin-Karp, but useful far beyond it), and to place string algorithms within this guideβs broader pattern-recognition framework.
Purpose: Knowing how KMP works is not the same as recognizing, three months later, that a brand-new problem is secretly a KMP problem. This chapterβs purpose is that second, harder skill.
Problem solved: Given a new, unfamiliar string problem, correctly identify whether it calls for exact pattern matching (KMP/Z), approximate/multi-pattern/hash-based matching (Rabin-Karp/Rolling Hash), or prefix-structure exploitation (Trie) β and know why.
2. Intuition
Revisit the core intuition from the Data Structures guideβs String chapter: brute-force string matching wastes time because it βforgetsβ everything it learned about a partial match the moment a mismatch occurs, and starts over from scratch. Every efficient string algorithmβs entire value proposition is finding a way to NOT forget that information:
- KMPβs LPS array remembers βhow much of what Iβve already matched is also a valid prefix, so I can resume from there instead of restarting.β
- The Z-Function remembers βhow far does the match against the stringβs own prefix extend at every position,β a single array answering many different structural questions at once.
- Rabin-Karpβs rolling hash remembers a numeric fingerprint of the current window, updatable in O(1) as the window slides, rather than re-fingerprinting from scratch.
- A Trie remembers shared prefixes structurally, so a family of strings sharing a prefix only pays for that prefixβs storage/traversal once.
Recognizing which piece of βmemoryβ a new problem needs is the actual skill this chapter targets.
3. Step-by-Step Working
(a) Rolling Hash, formalized as its own tool (the engine inside Rabin-Karp)
A rolling hash lets you maintain a hash of a sliding window in O(1) per slide, rather than O(window size). The general technique (already shown in the Data Structures guide for Rabin-Karp) generalizes beyond exact pattern matching:
Polynomial rolling hash of a string s (treating characters as digits in base B, modulo M):
hash(s) = (s[0]*B^(L-1) + s[1]*B^(L-2) + ... + s[L-1]*B^0) mod M
Sliding from window [i, i+L-1] to [i+1, i+L]:
newHash = ( (oldHash - s[i]*B^(L-1)) * B + s[i+L] ) mod M
"remove the outgoing character's contribution" "shift everything up, add the new character"
Beyond simple pattern matching, rolling hash directly enables:
- Finding the longest duplicated substring in a text (binary search on the length β Chapter 1 β combined with a rolling-hash-based set of all substrings of that length, checking for a collision).
- Comparing substrings for equality in O(1) after O(n) preprocessing (precompute all prefix hashes; then any substringβs hash is derivable in O(1) via the same subtraction trick prefix sums use β directly connecting back to Chapter 9βs Prefix Sum, since a rolling/prefix hash IS structurally a prefix sum in a different number base).
- Detecting duplicate substrings/plagiarism across large documents by comparing hash sets rather than raw substrings.
(b) Pattern Recognition β mapping problem phrasing to the right technique
"Does text contain pattern, find all occurrences" (single pattern, exact)
β KMP or Z-Function (Data Structures guide, Ch. 2)
"Does text contain ANY of these many patterns" (multi-pattern)
β Rabin-Karp with multiple hashes, or Aho-Corasick (a Trie + KMP-failure-function hybrid,
an advanced extension worth knowing exists even without full implementation here)
"Compare many substrings for equality repeatedly" / "find longest duplicated substring"
β Rolling Hash (precomputed prefix hashes + O(1) substring hash queries)
"Autocomplete", "does any word start with this prefix", "longest common prefix of many strings"
β Trie (Data Structures guide, Ch. 9)
"Find the longest palindromic substring/subsequence"
β Expand-around-center (O(nΒ²)) for substring; Dynamic Programming (Ch. 12-13, LCS-style β
a palindrome IS the LCS of a string and its reverse) for subsequence; Manacher's algorithm
(an advanced O(n) technique, overview-level: uses a similar "don't recompute known
information" insight as KMP, applied to palindrome radii instead of prefix matches)
"Edit distance between two strings" (insert/delete/replace operations)
β Dynamic Programming (Ch. 13's LCS family, generalized to three operations instead of two)
"Anagram / character frequency matching within a sliding window"
β Sliding Window (Ch. 8) + a frequency array/hash map
4. Complexity Analysis
Rolling Hash (build + query): O(n) to precompute all prefix hashes of a string of length n; O(1) per substring-equality query afterward (via the same subtraction-based range trick as Prefix Sum, Chapter 9) β though note this is a probabilistic guarantee (hash collisions are possible, if rare with a good modulus), unlike KMP/Zβs airtight worst-case correctness.
Why rolling hash queries are O(1) β the same reasoning as Prefix Sum: once prefix hashes are precomputed, any substringβs hash is derivable via subtraction from two precomputed values, exactly like a range-sum query β this is not a coincidence; a polynomial rolling hash IS mathematically a prefix sum, just computed in a different base with modular arithmetic.
Recap of the core three algorithmsβ complexities (fully derived in the Data Structures guide, Chapter 2):
| Algorithm | Time | Guarantee |
|---|---|---|
| KMP | O(n+m) | Worst-case guaranteed |
| Z-Function | O(n+m) | Worst-case guaranteed |
| Rabin-Karp | O(n+m) expected | Probabilistic (collision risk) |
5. Advantages
- Rolling Hash generalizes far beyond simple pattern matching β substring equality comparison, duplicate detection, and plagiarism-style matching all reuse the identical O(1)-per-slide-update mechanism.
- Recognizing the shape of a string problem (single-pattern exact match vs. multi-pattern vs. prefix-structure vs. hash-comparison) is a transferable skill that generalizes to novel problems you havenβt seen before, unlike memorizing individual algorithms in isolation.
- The connection between rolling hash and prefix sum (both are βprecompute cumulative information, derive any range via subtractionβ) reinforces a pattern that recurs constantly throughout this entire guide.
6. Limitations
- Rolling hash is fundamentally probabilistic β a hash collision (two different substrings hashing identically) is possible, if rare with a well-chosen large prime modulus; applications requiring airtight correctness (security-sensitive matching) should prefer KMP/Z-Function or verify hash matches with a direct character comparison (as the Data Structures guideβs Rabin-Karp implementation already does).
- Aho-Corasick (multi-pattern matching) is mentioned here only at the overview level β implementing it fully requires combining a Trieβs structure with KMP-style failure links, a genuinely more advanced undertaking beyond this chapterβs scope.
- Manacherβs algorithm (O(n) palindrome detection) is similarly mentioned only at the overview level β the DP-based or expand-around-center approaches are more commonly expected in standard interviews, with Manacherβs reserved for specifically palindrome-heavy competitive programming contexts.
7. Real-World Applications
(Already covered in depth in the Data Structures guideβs String chapter for KMP/Z/Rabin-Karp specifically β text editors, search engines, bioinformatics, network security, plagiarism detection. Rolling Hashβs applications extend further:)
- Plagiarism/Duplicate Detection Systems: comparing large documents via rolling-hash fingerprints of substrings (shingling techniques) rather than raw text comparison β this is how many real plagiarism detectors and βsimilar documentβ search features work at scale.
- Version Control / Deduplication: systems like rsync and git use rolling-hash-based techniques (specifically, a form related to Rabin fingerprinting) to detect which parts of a file have changed without re-transmitting/re-storing unchanged content.
- Distributed Systems: content-addressable storage and chunk-based deduplication (e.g., in backup systems) commonly use rolling hashes to find chunk boundaries.
8. C++ Implementation
#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
// Rolling Hash utility class: precompute prefix hashes, then answer O(1) substring hash queries.
// This generalizes the Rabin-Karp rolling hash (Data Structures guide, Ch.2) into a reusable tool.
class RollingHash {
private:
std::vector<long long> prefixHash;
std::vector<long long> powers;
static const long long BASE = 131;
static const long long MOD = 1000000007LL;
public:
explicit RollingHash(const std::string& s) {
int n = s.size();
prefixHash.assign(n + 1, 0);
powers.assign(n + 1, 1);
for (int i = 0; i < n; ++i) {
prefixHash[i + 1] = (prefixHash[i] * BASE + s[i]) % MOD;
powers[i + 1] = (powers[i] * BASE) % MOD;
}
}
// Hash of substring s[l..r] (inclusive, 0-indexed). O(1) β the same subtraction
// trick as Prefix Sum (Chapter 9), just in modular arithmetic over a different base.
long long substringHash(int l, int r) const {
long long result = (prefixHash[r + 1] - prefixHash[l] * powers[r - l + 1]) % MOD;
return (result + MOD) % MOD; // ensure non-negative result under modular arithmetic
}
};
// Find the longest duplicated substring using Binary Search (Ch.1) + Rolling Hash.
// O(n log n) expected β binary search over length, O(n) hash-collision check per length.
std::string longestDuplicateSubstring(const std::string& s) {
RollingHash rh(s);
int n = s.size();
int lo = 1, hi = n - 1, bestLen = 0, bestStart = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2; // candidate LENGTH to check (binary search on the answer β Ch.1)
std::unordered_set<long long> seen;
int foundStart = -1;
for (int i = 0; i + mid <= n; ++i) {
long long h = rh.substringHash(i, i + mid - 1);
if (seen.count(h)) { foundStart = i; break; } // hash collision candidate β a probable duplicate
seen.insert(h);
}
if (foundStart != -1) {
bestLen = mid; bestStart = foundStart;
lo = mid + 1; // try for an even longer duplicate
} else {
hi = mid - 1; // no duplicate of this length β try shorter
}
}
return bestStart == -1 ? "" : s.substr(bestStart, bestLen);
}
// Example usage
int main() {
RollingHash rh("abcabc");
std::cout << "hash(0,2) == hash(3,5)? "
<< (rh.substringHash(0, 2) == rh.substringHash(3, 5)) << "\n"; // 1 (true) β both are "abc"
std::cout << "Longest duplicate substring in \"banana\": \""
<< longestDuplicateSubstring("banana") << "\"\n"; // "ana"
return 0;
}
9. Code Walkthrough
RollingHashβs constructor precomputing BOTHprefixHashandpowers:powers[k]storesBASE^k mod MOD, needed becausesubstringHashβs subtraction trick must βshiftβ the left boundaryβs contribution by the correct power of the base before subtracting β precomputing these powers once avoids recomputingBASE^kfrom scratch (which would cost O(k) via naive exponentiation) on every query.substringHashβs formula, directly mirroring Prefix Sumβssum(L,R) = prefix[R] - prefix[L-1]: here itβsprefixHash[r+1] - prefixHash[l] * powers[r-l+1], with the extra multiplication bypowers[...]needed because, unlike simple addition (where every position contributes equally), each characterβs contribution to a polynomial hash depends on its position, so removing the correct number of leading charactersβ worth of βpositional weightβ requires this extra scaling factor.- The
+ MOD) % MODat the end: modular subtraction in C++ can produce a negative intermediate result (since%can return negative values for negative operands) β addingMODbefore the final modulo ensures a correctly non-negative result, the exact same defensive pattern used in the Data Structures guideβs Rabin-Karp implementation. longestDuplicateSubstringβs binary-search-on-the-answer structure: This is a direct, concrete reuse of Chapter 1βs technique β βis there a duplicate substring of lengthmid?β is a monotonic yes/no predicate (if a duplicate of length L exists, one of length L-1 trivially also exists, by just truncating it), making binary search over the candidate length valid and correct.- Why a hash COLLISION here is only a βcandidate,β not proof: strictly speaking, a full implementation should verify a hash match with a direct substring comparison (as the Data Structures guideβs Rabin-Karp does) before accepting it as a genuine duplicate β omitted here for clarity, but essential in production code to eliminate the (rare) false-positive risk.
Common mistakes to watch for here:
- Forgetting the positional-weight scaling factor (
powers[...]) in the substring hash subtraction β a very easy detail to miss when adapting the simple Prefix Sum formula to this modular, positionally-weighted context. - Not verifying a hash βmatchβ with a direct character comparison before treating it as a confirmed duplicate β risks a (rare but real) false positive from a hash collision.
- Using a small modulus or predictable base, increasing collision risk β always prefer a large prime modulus, as shown.
10. Dry Run
RollingHash("abcabc").substringHash(0,2) vs. substringHash(3,5) β both should equal the hash of βabcβ:
prefixHash computed incrementally as: a, ab, abc, abca, abcab, abcabc (each step: prev*BASE + char, mod MOD)
substringHash(0,2) = prefixHash[3] - prefixHash[0]*powers[3]
= hash("abc") - 0*powers[3]
= hash("abc")
substringHash(3,5) = prefixHash[6] - prefixHash[3]*powers[3]
= hash("abcabc") - hash("abc")*BASEΒ³
= [removes the "abc" prefix's positional contribution from the full "abcabc" hash,
leaving exactly the hash equivalent of the trailing "abc"]
Both evaluate to the same numeric value (modulo the astronomically unlikely event of an
unrelated hash collision) β confirming both substrings are "abc". β
11. Complexity Table
| Technique | Time | Space | Guarantee |
|---|---|---|---|
| KMP / Z-Function (recap) | O(n+m) | O(m) / O(n+m) | Worst-case exact |
| Rabin-Karp (recap) | O(n+m) expected | O(1) | Probabilistic |
| Rolling Hash (build + query) | O(n) build, O(1) query | O(n) | Probabilistic |
| Longest Duplicate Substring (binary search + rolling hash) | O(n log n) expected | O(n) | Probabilistic |
| Trie (recap, Data Structures guide Ch.9) | O(L) per op | O(total chars) | Exact |
Every entry explained: Rolling Hashβs O(1) query cost is identical in structure to Prefix Sumβs O(1) query cost (Chapter 9) β both trade O(n) upfront preprocessing for O(1) answers to a large number of subsequent range-style queries, differing only in whatβs being aggregated (sums vs. positional hash values) and the resulting correctness guarantee (exact for sums, probabilistic for hashes).
12. Common Mistakes
- Forgetting hash verification β treating a rolling-hash match as proof rather than a strong candidate needing confirmation.
- Misapplying the positional-weight scaling factor when adapting the Prefix Sum subtraction pattern to rolling hashβs modular, position-sensitive context.
- Choosing a poor base/modulus combination, increasing real-world collision risk β always use a large prime modulus and a base larger than the alphabet size.
- Not recognizing when a problem is secretly Trie-shaped, KMP-shaped, or Rolling-Hash-shaped β the biggest practical risk in this entire chapter is pattern-recognition failure, not implementation error; always ask βam I dealing with single exact matching, multi-pattern matching, prefix structure, or repeated substring comparison?β before choosing a tool.
- Reaching for Dynamic Programming (Edit Distance, palindrome subsequence) when a simpler, faster string-specific technique would do, or vice versa β always check whether the problemβs core need is genuinely βcompare/align two sequences with flexible operationsβ (DPβs territory) versus βmatch/search within one sequenceβ (KMP/Z/Rabin-Karp/Trieβs territory).
13. Interview Questions
Conceptual:
- Explain why a polynomial rolling hash is mathematically a prefix sum in a different number base.
- When would you choose Rolling Hash over KMP/Z-Function for a pattern-matching task, given Rolling Hashβs probabilistic nature?
- How does binary-search-on-the-answer (Chapter 1) combine with Rolling Hash to solve Longest Duplicate Substring?
- What is Aho-Corasick, conceptually, and what two techniques does it combine?
- Given a new, unfamiliar string problem, walk through your process for identifying which technique applies.
Coding:
- Implement a reusable Rolling Hash class supporting O(1) substring comparison.
- Longest Duplicate Substring (LeetCode 1044) β binary search + rolling hash.
- Repeated DNA Sequences (LeetCode 187) β direct rolling-hash application.
- Shortest Palindrome (LeetCode 214) β KMP-based approach (recap from Data Structures guide Ch.2).
- Implement strStr() using each of KMP, Z-Function, and Rabin-Karp β compare all three side by side.
Follow-ups / interviewer traps:
- βYour rolling hash found a match β are you certain itβs a real match?β (tests whether the candidate remembers to verify with direct comparison, guarding against collision-based false positives)
- βCan you extend Rolling Hash to 2D (matching a small grid pattern within a larger grid)?β (tests generalizing the 1D technique β yes, via a 2D polynomial hash, analogous to the Data Structures guideβs 2D Prefix Sum)
- βWhy might an interviewer prefer you use KMP over Rabin-Karp for a security-sensitive string-matching feature?β (tests understanding of the exact-vs-probabilistic guarantee distinction and its real-world stakes)
14. Practice Problems
Easy
- Implement strStr() (LeetCode 28) β solve with all three techniques for comparison
Medium
- Repeated DNA Sequences (LeetCode 187)
- Longest Happy Prefix (LeetCode 1392) β recap from Data Structures guide Ch.2
- Find All Anagrams in a String (LeetCode 438) β Sliding Window + frequency map (Ch.8), not string-matching-specific
Hard
- Longest Duplicate Substring (LeetCode 1044)
- Shortest Palindrome (LeetCode 214)
- Distinct Echo Substrings (LeetCode 1316) β rolling hash + set-based duplicate detection
Also recommended: revisit the Data Structures guideβs Chapter 2 practice problems (KMP/Z/Rabin-Karp) alongside this chapterβs rolling-hash-specific problems to build a complete, tested string-algorithms toolkit.
15. Summary
Key takeaways:
- Every efficient string algorithmβs core value is βnot forgetting information a naive approach would discardβ β KMP/Z remember prefix-overlap structure; Rabin-Karp/Rolling Hash remember a numeric fingerprint updatable in O(1); Trie remembers shared prefixes structurally.
- Rolling Hash is mathematically a prefix sum in a different number base β recognizing this connection (rather than treating it as an unrelated new technique) reinforces the βprecompute cumulative info, derive ranges via subtractionβ pattern that recurs throughout this guide.
- The hardest and most valuable skill in this entire chapter β and arguably this entire guide β is pattern recognition: correctly identifying which of these techniques (or which combination) a novel, unfamiliar problem actually calls for.
Complexity recap:
| Time | Guarantee | |
|---|---|---|
| KMP / Z-Function | O(n+m) | Exact, worst-case |
| Rabin-Karp / Rolling Hash | O(n+m) expected | Probabilistic |
| Trie | O(L) per operation | Exact |
Decision guide: Single-pattern exact matching with an airtight guarantee β KMP or Z-Function. Multi-pattern or substring-comparison-heavy problems where a small collision risk is acceptable β Rolling Hash / Rabin-Karp. Prefix-structure-heavy problems (autocomplete, dictionary matching) β Trie. Sequence-alignment problems with flexible edit operations β Dynamic Programming (Chapters 12-13). Whenever unsure, ask: βis this about finding an exact pattern, comparing many substrings, exploiting shared prefixes, or aligning two sequences with edits?β β the answer points directly at the right tool.
Guide Complete β Final Reflection
This completes The Algorithms Handbook, spanning: the Complexity Analysis primer β Binary Search β Sorting (Simple, Merge, Quick, Heap, Non-Comparison) β Two Pointer / Sliding Window / Prefix Sum β Greedy β Backtracking β Dynamic Programming (Fundamentals and Classic Problems) β Graph Algorithms (extending the Data Structures guide with Floyd-Warshall and cycle detection) β Tree Algorithms β String Algorithms.
The throughline worth carrying forward, echoing the companion Data Structures guideβs own closing reflection: almost every algorithm in this guide is either (a) a clever way of not repeating work youβve already done β memoization, rolling hashes, prefix sums, the LPS array, all fundamentally the same idea applied in different contexts β or (b) a provable argument for why a greedy local choice is globally safe, when such an argument exists, and a fallback to systematic exhaustive search (backtracking) or careful state-tracking (DP) when it doesnβt. When you meet an unfamiliar algorithm in the future, asking βwhat redundant work is this avoiding, and why is that avoidance provably correct?β will get you most of the way to understanding it β the same lens this entire guide has used, chapter after chapter.
Chapter 17: Advanced Dynamic Programming (Bitmask DP, DP on Trees)
Study time: ~6-7 hours | Prerequisite: DP Fundamentals & Classic Problems (Ch. 12-13), Tree Algorithms (Ch. 15), bitwise operators | Difficulty: Advanced
1. Introduction
Definition: This chapter extends Dynamic Programmingβs core idea β cache the answer to each distinct subproblem, solve each exactly once β to two more sophisticated state representations: Bitmask DP, where the DP state includes a bitmask encoding βwhich subset of items/vertices has been used so far,β and DP on Trees, where the DP state is defined per tree node and combines information from that nodeβs children (a direct generalization of Tree Diameterβs βcombine a bottom-up value with somethingβ pattern from Chapter 15).
Purpose: Many real optimization problems canβt be solved with the simple 1D or 2D DP states from Chapters 12-13 β they need to track βexactly which subset of elements have I already committed toβ (Bitmask DP) or need an answer computed for every node of a hierarchical structure, incorporating each nodeβs childrenβs answers (DP on Trees). This chapter shows how the same core DP methodology β state, transition, base case β extends cleanly to both.
Problem solved: Optimization problems over small (typically n β€ ~20) sets where the specific subset used matters (Traveling Salesman Problem, assignment problems) β Bitmask DP; and optimization/counting problems defined recursively over a treeβs structure (maximum independent set in a tree, counting subtrees with a property) β DP on Trees.
2. Intuition
Bitmask DP: if you need to track βwhich specific subset of n items has been usedβ as part of your DP state (not just βhow many,β but which ones), and n is small (typically β€ 20 or so), you can represent that subset as a single integer β bit i set to 1 means βitem i is included.β This integer becomes part of your DP state alongside whatever else youβre tracking (e.g., dp[mask][i] = βbest value achievable having used exactly the items in mask, currently positioned at item iβ). The reason this works at all is that a bitmask is just a compact, O(1)-comparable, O(1)-updatable encoding of a subset β checking βis item j in this subset?β or βadd item j to this subsetβ are both single bitwise operations.
DP on Trees: this is the direct generalization of Tree Diameter (Chapter 15) β instead of computing one global number (the diameter), you compute a DP value at every node, where that nodeβs value depends on combining its childrenβs already-computed DP values. The recursive structure βprocess children first (post-order), then combine their results to compute the current nodeβs answerβ is identical to Tree Diameterβs height computation β DP on Trees is really βDP where the state graph happens to be a treeβ rather than a fundamentally different technique.
3. Step-by-Step Working
(a) Traveling Salesman Problem (TSP) via Bitmask DP β 4 cities
Distance matrix (4 cities, 0-indexed), start/end at city 0:
0 1 2 3
0 [ 0, 10, 15, 20]
1 [ 10, 0, 35, 25]
2 [ 15, 35, 0, 30]
3 [ 20, 25, 30, 0]
STATE: dp[mask][i] = minimum cost to have visited exactly the cities in `mask`,
currently standing at city i (having started at city 0).
BASE CASE: dp[{0}][0] = 0 (mask with only bit 0 set, standing at city 0, cost 0 β haven't moved yet)
TRANSITION: dp[mask][i] = min over all j in mask, j != i, where mask WITHOUT i
was reachable ending at j:
dp[mask][i] = min( dp[mask ^ (1<<i)][j] + dist[j][i] ) for all valid j
Building up (mask represented in binary, bit i = "city i visited"):
dp[0001][0] = 0 (just city 0)
dp[0011][1] = dp[0001][0] + dist[0][1] = 0+10 = 10 (visited {0,1}, at city 1)
dp[0101][2] = dp[0001][0] + dist[0][2] = 0+15 = 15 (visited {0,2}, at city 2)
dp[1001][3] = dp[0001][0] + dist[0][3] = 0+20 = 20 (visited {0,3}, at city 3)
dp[0111][2] = min( dp[0011][1]+dist[1][2] ) = 10+35 = 45 (visited {0,1,2}, at city 2, via 1)
dp[1011][3] = min( dp[0011][1]+dist[1][3] ) = 10+25 = 35 (visited {0,1,3}, at city 3, via 1)
dp[1101][3] = min( dp[0101][2]+dist[2][3] ) = 15+30 = 45 (visited {0,2,3}, at city 3, via 2)
dp[1101][1] = min( dp[1001][3]+dist[3][1] ) = 20+25 = 45 ... (continuing all valid combinations)
dp[1111][3] = min over ways to reach {0,1,2,3} ending at 3:
= min( dp[0111][2]+dist[2][3], dp[1011][1]+dist[1][3], ... )
= min( 45+30, ... ) = 75 (one candidate; full computation checks all predecessors)
FINAL ANSWER = min over all i of ( dp[1111][i] + dist[i][0] ) β return to start!
Why this beats brute-force permutation checking: brute force tries all (n-1)! orderings of the remaining cities β for n=4, thatβs 6, trivial, but for n=15 itβs over 87 billion. Bitmask DP instead has 2βΏ Γ n states (mask Γ current city), each computed in O(n) β for n=15, thatβs 2^15 Γ 15 Γ 15 β 7.4 million operations, dramatically more tractable.
(b) Maximum Independent Set in a Tree β DP on Trees
Tree: 1
/ \
2 3
/ \
4 5
GOAL: select a subset of nodes such that no two selected nodes are directly
connected (an edge), maximizing the COUNT of selected nodes.
STATE (per node, two values):
dp[node][0] = max independent set size in this node's subtree, NODE NOT INCLUDED
dp[node][1] = max independent set size in this node's subtree, NODE INCLUDED
TRANSITION (post-order β children computed first):
dp[node][1] = 1 + sum( dp[child][0] for every child ) (if we include node, children CANNOT be included)
dp[node][0] = sum( max(dp[child][0], dp[child][1]) for every child ) (if we exclude node, children are free to choose either)
Leaves first:
dp[4][0]=0, dp[4][1]=1 (leaf: including it gives 1, excluding gives 0)
dp[5][0]=0, dp[5][1]=1
Node 2 (children 4, 5):
dp[2][1] = 1 + dp[4][0] + dp[5][0] = 1+0+0 = 1
dp[2][0] = max(dp[4][0],dp[4][1]) + max(dp[5][0],dp[5][1]) = 1+1 = 2
Node 3 (leaf):
dp[3][0]=0, dp[3][1]=1
Node 1 (children 2, 3):
dp[1][1] = 1 + dp[2][0] + dp[3][0] = 1+2+0 = 3
dp[1][0] = max(dp[2][0],dp[2][1]) + max(dp[3][0],dp[3][1]) = max(2,1) + max(0,1) = 2+1 = 3
FINAL ANSWER = max(dp[1][0], dp[1][1]) = max(3,3) = 3
(e.g., select {4, 5, 3} β none of these three are directly connected β size 3)
4. Complexity Analysis
Bitmask DP (TSP-style): O(2βΏ Β· nΒ²) time β 2βΏ possible masks, n possible βcurrent cityβ values per mask (so 2βΏΒ·n states total), and each stateβs transition checks up to n possible predecessors β giving 2βΏ Β· n Β· n = O(2βΏ Β· nΒ²). Space: O(2βΏ Β· n) for the DP table.
Why this is a massive improvement over brute forceβs O(n!): for even modest n (15-20), 2βΏΒ·nΒ² is dramatically smaller than n! β this is the entire value proposition of recognizing a problem as Bitmask-DP-shaped rather than attempting brute-force permutation enumeration. That said, Bitmask DPβs own exponential factor (2βΏ) means itβs only practical for small n (typically β€ 20-22 given realistic time limits) β it doesnβt escape exponential complexity entirely, it just has a much better exponential base/exponent combination than raw permutation enumeration.
DP on Trees: O(n) time β a single post-order traversal, computing O(1) (or O(number of children) for the summation) work at each node, summing to O(n) total across the whole tree, identical in spirit to Tree Diameterβs O(n) complexity (Chapter 15) β the tree-shaped state space, visited exactly once via post-order, is what keeps this linear rather than exponential.
5. Advantages
- Bitmask DP makes previously-infeasible small-to-medium subset-optimization problems (TSP, assignment problems) tractable, extending DPβs reach to state spaces that a simple 1D/2D array canβt represent.
- DP on Trees directly reuses the post-order βcombine childrenβs resultsβ pattern already familiar from Tree Diameter β no fundamentally new mental model needed, just a broader recognition of when a problemβs natural recursive structure follows a tree.
- Both techniques demonstrate that βdefine the right stateβ (Chapter 12βs central lesson) generalizes far beyond simple array-indexed states β a state can be a bitmask, a tree node, or in principle any efficiently-comparable/hashable representation of βwhat matters about where I am in the problem.β
6. Limitations
- Bitmask DPβs
O(2βΏ)factor makes it fundamentally impractical beyond roughly n=20-22 (2^22 β 4 million masks, already substantial when multiplied by n and further transition costs) β itβs a tool for small subset-sensitive problems, not a general-purpose optimization technique. - DP on Trees requires the underlying problem to genuinely decompose along the tree structure (a nodeβs answer depends only on its subtree, or can be correctly computed via a second pass for βanswers depending on the rest of the tree too,β a more advanced technique called re-rooting, beyond this chapterβs scope).
- Both techniques require correctly identifying a genuinely more complex state than Chapters 12-13βs simpler DP problems β a harder skill requiring more practice to internalize.
7. Real-World Applications
- Bitmask DP: the Traveling Salesman Problem itself has direct applications in logistics/delivery route optimization (for small numbers of stops), circuit board drilling path optimization (minimizing tool travel distance), and DNA fragment assembly (finding optimal orderings of small numbers of overlapping fragments).
- Assignment Problems (also Bitmask-DP-solvable for small n): assigning a small number of workers to tasks to minimize total cost, used in specialized small-scale resource allocation scenarios.
- DP on Trees: network design problems (e.g., minimum cost to cover a tree-structured network with monitoring stations), organizational optimization problems (maximum independent set in an org chart β e.g., βselect employees such that no manager-report pair is both selected,β directly relevant to certain incentive/survey-design problems), and phylogenetic tree analysis in bioinformatics.
- Compilers: register allocation and certain code-generation optimizations for expression trees use tree-structured DP.
- Game Development: skill-tree/tech-tree optimization (maximum value selectable subject to prerequisite/exclusivity constraints, when the tree is small) can use DP on Trees directly.
8. C++ Implementation
#include <iostream>
#include <vector>
#include <climits>
// ---------- BITMASK DP: Traveling Salesman Problem ----------
// O(2^n * n^2) time, O(2^n * n) space.
int tsp(const std::vector<std::vector<int>>& dist) {
int n = static_cast<int>(dist.size());
int fullMask = (1 << n) - 1;
// dp[mask][i] = min cost to visit exactly the cities in `mask`, currently at city i.
std::vector<std::vector<int>> dp(1 << n, std::vector<int>(n, INT_MAX));
dp[1][0] = 0; // start: only city 0 visited, standing at city 0, cost 0
for (int mask = 1; mask <= fullMask; ++mask) {
for (int i = 0; i < n; ++i) {
if (!(mask & (1 << i)) || dp[mask][i] == INT_MAX) continue; // city i not in mask, or unreachable
for (int j = 0; j < n; ++j) {
if (mask & (1 << j)) continue; // j already visited β can't revisit
int newMask = mask | (1 << j);
int newCost = dp[mask][i] + dist[i][j];
if (newCost < dp[newMask][j]) {
dp[newMask][j] = newCost; // found a cheaper way to reach (newMask, j)
}
}
}
}
// Return to the starting city (0) from wherever the tour ended, minimizing over all endpoints.
int best = INT_MAX;
for (int i = 1; i < n; ++i) {
if (dp[fullMask][i] != INT_MAX) {
best = std::min(best, dp[fullMask][i] + dist[i][0]);
}
}
return best;
}
// ---------- DP ON TREES: Maximum Independent Set ----------
struct TreeNode {
int id;
std::vector<TreeNode*> children;
};
// Returns {excluded, included} best sizes for the subtree rooted at `node`. O(n) overall.
std::pair<int,int> maxIndependentSetHelper(TreeNode* node) {
int excludedSum = 0, includedSum = 1; // includedSum starts at 1 for THIS node being included
for (TreeNode* child : node->children) {
auto [childExcluded, childIncluded] = maxIndependentSetHelper(child);
excludedSum += std::max(childExcluded, childIncluded); // excluding this node: children are free to choose
includedSum += childExcluded; // including this node: children MUST be excluded
}
return {excludedSum, includedSum};
}
int maxIndependentSet(TreeNode* root) {
auto [excluded, included] = maxIndependentSetHelper(root);
return std::max(excluded, included);
}
// Example usage
int main() {
std::vector<std::vector<int>> dist = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};
std::cout << "TSP minimum tour cost: " << tsp(dist) << "\n"; // 80 (0->1->3->2->0)
// Build the tree: 1 -> (2 -> (4, 5)), (3)
TreeNode n4{4, {}}, n5{5, {}}, n3{3, {}};
TreeNode n2{2, {&n4, &n5}};
TreeNode n1{1, {&n2, &n3}};
std::cout << "Max Independent Set size: " << maxIndependentSet(&n1) << "\n"; // 3
return 0;
}
9. Code Walkthrough
tspβsdp[mask][i]table: Exactly the state described in section 3(a) βmask(an integer up to2βΏ-1) encodes exactly which cities have been visited, anditracks the current position. The double nested loop (mask, theni, thenj) tries extending every reachable(mask, i)state by visiting every not-yet-visited cityj, updatingdp[newMask][j]if this route is cheaper than any previously found.mask & (1 << i)andmask | (1 << i): These are the two fundamental bitmask operations this entire technique relies on β&checks membership (βis city i in this subset?β),|adds membership (βmark city i as now visitedβ). Both are O(1), which is exactly what makes representing a subset as an integer so efficient compared to, say, astd::set<int>.- The final loop returning to city 0: TSP requires a complete cycle (return to the start), so after finding the cheapest way to visit all cities ending at each possible city
i, we add the direct return-trip costdist[i][0]and take the minimum across all such completions. maxIndependentSetHelperβs structured binding return{excluded, included}: Directly mirrors Tree Diameterβs dual-purpose recursive return (Chapter 15) β this function returns TWO values needed by the parentβs own computation, rather than a single aggregate, because the parent needs to know both βwhatβs the best subtree answer if I DONβT include myselfβ and ββ¦if I DO include myselfβ to correctly compute its own two values in turn.includedSum += childExcluded(notchildIncluded): This is the entire independent-set constraint encoded in one line β if the current node IS included, none of its direct children can also be included (that would create a forbidden adjacent pair), so weβre forced to add each childβsexcludedvalue specifically, never itsincludedvalue.
Common mistakes to watch for here:
- Off-by-one or incorrect bit-shift arithmetic when checking/setting mask bits β always double-check
1 << ivs1 << (i-1)conventions match your indexing scheme consistently. - In Bitmask DP, forgetting to skip already-visited cities (
if (mask & (1<<j)) continue;) when considering transitions, which would allow revisiting a city β invalid for TSP. - In DP on Trees, using
childIncludedinstead ofchildExcludedwhen computingincludedSumβ this single swap breaks the core independent-set constraint entirely, silently allowing adjacent selected nodes. - Not initializing unreachable
dp[mask][i]states to a proper βinfinityβ sentinel, risking incorrectmincomparisons.
10. Dry Run
maxIndependentSet, fully traced in section 3(b) β leaves 4 and 5 each contribute (excluded=0, included=1); node 2 combines them into (excluded=2, included=1); node 3 (leaf) is (excluded=0, included=1); node 1 combines node 2 and node 3 into (excluded=3, included=3); final answer max(3,3)=3. This matches the codeβs expected output exactly, confirming the recursive combination logic.
11. Complexity Table
| Technique | Time | Space | Practical limit |
|---|---|---|---|
| Bitmask DP (TSP-style) | O(2βΏ Β· nΒ²) | O(2βΏ Β· n) | n β² 20-22 |
| DP on Trees | O(n) | O(h) recursion stack | No practical limit beyond tree size/recursion depth |
Every entry explained: Bitmask DPβs exponential factor is unavoidable for exact TSP-style solutions (TSP itself is NP-hard; Bitmask DP is a genuine improvement over brute-force permutations, but doesnβt escape exponential complexity, only a better exponential base) β this caps its practical applicability to small n. DP on Trees, by contrast, is genuinely linear, since the tree structure itself (visited once via post-order) bounds total work, with no combinatorial explosion analogous to Bitmask DPβs subset-tracking.
12. Common Mistakes
- Attempting Bitmask DP on problems with n much larger than ~20 β the exponential blowup makes this simply infeasible; recognize this limit before committing to the approach.
- Bitwise operator precedence errors β
mask & 1 << iwithout parentheses can silently misbehave due to operator precedence; always parenthesize bitwise operations explicitly (mask & (1 << i)). - Confusing which child value to use in DP on Treesβ inclusion/exclusion transitions β always re-derive the constraint from scratch (what does including THIS node force about its children?) rather than pattern-matching from memory.
- Not handling the treeβs root correctly β DP on Treesβ final answer typically needs
max(dp[root][0], dp[root][1])or similar, since the root has no parent constraining it either way. - Forgetting that Bitmask DPβs mask must be initialized/interpreted consistently (bit i = city/item i) across the entire implementation β inconsistent conventions between different parts of the code are a common source of confusion.
13. Interview Questions
Conceptual:
- Why does Bitmask DP improve on brute-force permutation enumeration for TSP, despite still being exponential?
- Whatβs the practical size limit for Bitmask DP, and why?
- Explain how DP on Treesβ state design directly generalizes Tree Diameterβs approach from Chapter 15.
- Why does including a node in a Maximum Independent Set force its children to be excluded, and how is this encoded in the DP transition?
- When would you recognize a problem as βBitmask-DP-shapedβ versus a simpler 1D/2D DP?
Coding:
- Implement TSP via Bitmask DP, including path reconstruction (not just the minimum cost).
- Partition to K Equal Sum Subsets (LeetCode 698) β a Bitmask DP application.
- Maximum Independent Set in a Tree (as implemented above).
- House Robber III (LeetCode 337) β Maximum Independent Set applied to a binary tree specifically.
- Shortest Hamiltonian Path (a TSP variant without the return-to-start requirement).
Follow-ups / interviewer traps:
- βYour Bitmask DP works for n=15 β what about n=25?β (tests recognizing the fundamental exponential limit and knowing to pivot to an approximation algorithm or heuristic instead of forcing an infeasible exact approach)
- βCan DP on Trees handle a nodeβs answer depending on information from OUTSIDE its own subtree (e.g., the rest of the tree)?β (tests awareness of re-rooting techniques, an advanced extension beyond this chapterβs basic treatment)
- βHouse Robber III β how does this map exactly onto Maximum Independent Set?β (tests recognizing that βhouses form a binary tree, canβt rob two directly connected housesβ is a verbatim restatement of the Maximum Independent Set problem)
14. Practice Problems
Medium
- House Robber III (LeetCode 337)
- Partition to K Equal Sum Subsets (LeetCode 698)
Hard
- Traveling Salesman Problem (GeeksforGeeks classic; also appears in various forms across competitive programming judges)
- Shortest Path Visiting All Nodes (LeetCode 847) β Bitmask DP applied to a graph traversal
- Maximum Students Taking Exam (LeetCode 1349) β Bitmask DP over grid rows
- Binary Tree Cameras (LeetCode 968) β a DP-on-Trees variant with a three-state transition
Also recommended: GeeksforGeeks βBitmasking and Dynamic Programmingβ and βDP on Treesβ practice sets; implement TSP for n up to 15-18 and observe the practical runtime scaling firsthand.
15. Summary
Key takeaways:
- Bitmask DP extends DPβs state to include βexactly which subset has been used,β valid and efficient specifically for small n (β€ ~20-22) where 2βΏ is computationally manageable.
- DP on Trees is not a fundamentally new technique β itβs DP Fundamentalsβ state-transition-base-case methodology applied where the natural recursive structure happens to be a tree, directly generalizing Tree Diameterβs post-order βcombine childrenβs resultsβ pattern.
- Both techniques reinforce this guideβs central DP lesson from Chapter 12: correctly identifying the STATE is everything β a state can be an array index, a bitmask, or a tree node, as long as itβs a well-defined, efficiently comparable representation of βwhat matters right now.β
Complexity recap:
| Time | Practical limit | |
|---|---|---|
| Bitmask DP | O(2βΏ Β· poly(n)) | n β² 20-22 |
| DP on Trees | O(n) | Tree size / recursion depth |
Decision guide: Reach for Bitmask DP when a problemβs state genuinely needs to track βwhich specific subsetβ (not just a count) AND the relevant set size is small (β€20ish). Reach for DP on Trees whenever a problemβs natural structure is hierarchical and each nodeβs optimal answer depends on combining its childrenβs optimal answers β recognize this by asking βdoes this problemβs recursive structure decompose along parent-child relationships?β
Next chapter: 18_advanced_techniques.md β Meet in the Middle and Heavy-Light Decomposition (overview).
Chapter 18: Advanced Techniques β Meet in the Middle & Heavy-Light Decomposition (Overview)
Study time: ~4-5 hours | Prerequisite: Bitmask DP (Ch. 17), Binary Search (Ch. 1), Segment Tree (Data Structures guide, Ch. 15) | Difficulty: Advanced This is the final chapter of the Algorithms Handbook β both techniques here are marked βoverviewβ because theyβre competitive-programming-tier tools: valuable to know exist and understand conceptually, but less commonly required to implement from scratch in a standard software engineering interview.
1. Introduction
Definition: Meet in the Middle is a technique for problems with an exponential (typically 2βΏ) search space, that splits the problem in half, exhaustively solves each half separately (2^(n/2) each β dramatically smaller), and then combines the two halvesβ results efficiently (often via sorting + binary search, or a hash set). Heavy-Light Decomposition (HLD) is a technique for decomposing a tree into a small number of vertical βchains,β enabling path-based queries (sum/min/max along the path between two arbitrary nodes) to run in O(logΒ² n) by combining tree structure with a Segment Tree (Data Structures guide, Chapter 15) over each chain.
Purpose: Both techniques exist to defeat what would otherwise be prohibitively expensive brute-force approaches β Meet in the Middle turns O(2βΏ) into O(2^(n/2)), an enormous practical improvement even though both are technically exponential; Heavy-Light Decomposition turns βO(n) per path queryβ (a naive tree walk) into O(logΒ² n), enabling fast repeated path queries on large, dynamic trees.
Problem solved: Meet in the Middle handles subset-sum/subset-selection problems where n is too large for Bitmask DPβs O(2βΏ) (n up to ~35-40 instead of ~20-22) but still exponential in nature. Heavy-Light Decomposition handles βrepeated queries about the path between two arbitrary nodes in a tree, with possible updatesβ β a genuinely different problem shape than the single-source tree DP of Chapter 15.
2. Intuition
Meet in the Middle: if checking all 2βΏ subsets is too slow, but n is around 30-40 (too large for Bitmask DPβs 2βΏ table, but not enormous), split the n elements into two halves of n/2 each. Enumerate all 2^(n/2) subsets of the FIRST half (storing their sums, say), and all 2^(n/2) subsets of the SECOND half β then, for each combination, you need βdoes some subset-sum from half A plus some subset-sum from half B equal the target?β This βcombine two independently-generated lists to answer a combined queryβ step can often be done efficiently (sort one list, binary search into it for each element of the other β directly reusing Chapter 1), turning 2^(n/2) log(2^(n/2)) total work β astronomically better than 2βΏ for even moderately large n (e.g., n=40: 2^40 β 10^12, hopeless; 2^20 Β· 20 β 2Γ10^7, entirely tractable).
Heavy-Light Decomposition: the core problem with naive βwalk from node A up to the root, then down to node Bβ path queries is that a single path can span O(n) nodes in the worst case (a long, thin tree) β no way around visiting each node on the path at least once for an O(n)-per-query approach. HLDβs insight: decompose the tree into chains, where each chain is a maximal path through βheavyβ edges (an edge to the child with the largest subtree) β this decomposition guarantees that any root-to-node path crosses at most O(log n) different chains. Within each chain, a Segment Tree (Data Structures guide, Ch. 15) supports O(log n) range queries β so any path query decomposes into βat most O(log n) chains, each answerable in O(log n) via its Segment Tree,β giving O(logΒ² n) total.
3. Step-by-Step Working
(a) Meet in the Middle β Subset Sum, does any subset of [3, 34, 4, 12, 5, 2] sum to 9?
(A tiny example for illustration; Meet in the Middle's real value appears at nβ30-40,
where brute force's 2^n is intractable but 2^(n/2) is fine β shown small here for clarity.)
Split into two halves: A = [3, 34, 4], B = [12, 5, 2]
Enumerate ALL subset sums of A (2^3 = 8 subsets):
{} = 0, {3}=3, {34}=34, {4}=4, {3,34}=37, {3,4}=7, {34,4}=38, {3,34,4}=41
Enumerate ALL subset sums of B (2^3 = 8 subsets):
{} = 0, {12}=12, {5}=5, {2}=2, {12,5}=17, {12,2}=14, {5,2}=7, {12,5,2}=19
SORT the B-sums: [0, 2, 5, 7, 12, 14, 17, 19]
For each A-sum, binary search (Chapter 1) for (target - A-sum) within the sorted B-sums:
A-sum=0: need 9 in B-sums? not found.
A-sum=3: need 6 in B-sums? not found.
A-sum=34: need -25? not found (negative, skip).
A-sum=4: need 5 in B-sums? FOUND! (B-sum=5, from subset {5})
β Combined subset: {4} (from A) + {5} (from B) = {4,5}, sum = 9. β ANSWER FOUND.
Why this beats brute force: brute force checks all 2^6=64 subsets directly. Meet in the Middle checks 2^3+2^3=16 subset-generations plus a sort and 8 binary searches β for n=6 the difference is modest, but the growth rate difference is what matters: at n=40, brute force is 2^40 (infeasible) while Meet in the Middle is roughly 2^20 (very feasible).
(b) Heavy-Light Decomposition β conceptual chain identification
Tree (numbers = subtree sizes):
1 (7)
/ \
2 (4) 3 (2)
/ \ \
4 (2) 5 (1) 6 (1)
/
7 (1)
At node 1: children are 2 (subtree size 4) and 3 (subtree size 2).
HEAVY child = 2 (larger subtree) β edge 1-2 is a HEAVY edge, part of the same chain.
Edge 1-3 is a LIGHT edge β node 3 starts a NEW chain.
At node 2: children are 4 (subtree size 2) and 5 (subtree size 1).
HEAVY child = 4 β edge 2-4 is HEAVY, continues the same chain as 1-2.
Edge 2-5 is LIGHT β node 5 starts a new chain.
At node 4: only child is 7 (subtree size 1). Edge 4-7 is HEAVY (only option), continues the chain.
Resulting chains: {1,2,4,7} (the main heavy chain), {3,6}, {5}
A path query from 7 to 6 crosses: chain{1,2,4,7} (from 7 up to 1) then chain{3,6}
(from 1 down to 6) β just 2 chains, even though the raw node-path (7-4-2-1-3-6)
has 6 nodes β this compression from "path length" to "number of chains crossed"
is what HLD provides, and it's PROVABLY O(log n) chains for any path, regardless
of tree shape, because a light edge always at least halves the subtree size.
4. Complexity Analysis
Meet in the Middle: O(2^(n/2) Β· n) typically β generating each halfβs 2^(n/2) subsets costs O(2^(n/2) Β· n/2) (building each subset sum), and the combine step (sort + binary search) adds O(2^(n/2) log(2^(n/2))) = O(2^(n/2) Β· n). Overall, dominated by O(2^(n/2) Β· n) β compare directly to brute forceβs O(2βΏ): for n=40, 2^(n/2)Β·n β 2^20 Β· 40 β 4Γ10^7 (fast) versus 2^40 β 10^12 (far too slow).
Why splitting in half specifically is optimal: if you split into pieces of size k and n-k, total work is roughly 2^k + 2^(n-k) β this sum is minimized when k = n-k, i.e., an even split, which is why βmeet in the middleβ (not some other split ratio) is the right strategy.
Heavy-Light Decomposition: O(log n) chains per path (provably), O(logΒ² n) per path query β each of the O(log n) chains crossed requires an O(log n) Segment Tree range query, giving O(log n) Γ O(log n) = O(logΒ² n) total. Why at most O(log n) light edges appear on any path: every time you cross a light edge, you move from a subtree to a sibling subtree that is, by definition of βlight,β no larger than half the size of the subtree you just left (since the heavy child, by definition, has the largest subtree, at least half of the remaining size) β so the subtree size at least halves with every light edge crossed, meaning at most logβ n light edges can occur before the subtree size reaches 1.
5. Advantages
- Meet in the Middle extends exact brute-force-style subset search to roughly double the practical n (from ~20-22 with Bitmask DP to ~35-40), a substantial and often decisive improvement for specific problem sizes.
- Heavy-Light Decomposition provides a provable O(log n) bound on chains-per-path regardless of tree shape β a genuinely elegant structural guarantee, not a heuristic or average-case argument.
- Both techniques demonstrate a broader, transferable lesson: when a direct approach is exponential or linear-per-query and too slow, look for a way to split the problem into independently-solvable, efficiently-combinable pieces β the same βdivide, solve pieces, combineβ spirit as Merge Sort (Chapter 3), applied to fundamentally different problem shapes.
6. Limitations
- Meet in the Middle still has an exponential factor (
2^(n/2)) β it pushes the practical limit further than Bitmask DP but doesnβt escape exponential growth; for very large n, neither technique suffices, and approximation algorithms or heuristics become necessary instead. - Heavy-Light Decomposition is a genuinely complex technique to implement correctly β chain identification, Euler-tour-style indexing for the Segment Tree, and path-query logic that correctly handles crossing multiple chains all require careful, error-prone bookkeeping.
- Both are primarily competitive-programming and specialized-systems tools β most standard software engineering interviews are unlikely to require implementing either from scratch, though recognizing when theyβd apply (and being able to describe the approach) is valuable, higher-signal knowledge.
7. Real-World Applications
- Meet in the Middle: cryptography (some meet-in-the-middle attacks on double-encryption schemes are literally named after and structurally identical to this algorithmic technique β famously relevant to the historical weakness of naive Double-DES encryption); combinatorial optimization in operations research for moderately-sized exact subset-selection problems where full brute force is infeasible but the problem is too structurally irregular for DP.
- Heavy-Light Decomposition: used in specialized graph/network analysis tools requiring fast repeated path-aggregate queries on large, relatively static hierarchical structures (e.g., certain network topology analysis tools, some phylogenetic tree analysis software); competitive programming, where HLD-requiring problems are a well-known βhardβ category.
- Both techniquesβ underlying principles (divide a large space to make it tractable; decompose a structure to bound query cost) recur constantly in systems design even when the specific named technique isnβt directly applied β the thinking pattern transfers even when the exact algorithm doesnβt.
8. C++ Implementation
#include <iostream>
#include <vector>
#include <algorithm>
// ---------- MEET IN THE MIDDLE: Subset Sum ----------
// O(2^(n/2) * n) β generate all subset sums of each half, sort one, binary search the other.
void generateSums(const std::vector<int>& arr, int start, int end, std::vector<long long>& sums) {
int count = end - start;
for (int mask = 0; mask < (1 << count); ++mask) {
long long sum = 0;
for (int i = 0; i < count; ++i) {
if (mask & (1 << i)) sum += arr[start + i];
}
sums.push_back(sum);
}
}
bool subsetSumExists(const std::vector<int>& arr, long long target) {
int n = static_cast<int>(arr.size());
int mid = n / 2;
std::vector<long long> sumsA, sumsB;
generateSums(arr, 0, mid, sumsA); // all subset sums of the first half
generateSums(arr, mid, n, sumsB); // all subset sums of the second half
std::sort(sumsB.begin(), sumsB.end());
for (long long a : sumsA) {
long long needed = target - a;
if (std::binary_search(sumsB.begin(), sumsB.end(), needed)) { // Chapter 1's Binary Search, reused directly
return true;
}
}
return false;
}
// ---------- HEAVY-LIGHT DECOMPOSITION: conceptual skeleton (chain identification only) ----------
// A full HLD implementation (with Segment Tree integration for path queries) is substantial;
// this skeleton shows the CORE chain-decomposition logic that everything else builds on.
struct HLD {
std::vector<std::vector<int>> adj;
std::vector<int> subtreeSize, heavyChild, chainHead, parent, depth;
int n;
HLD(int n) : n(n), adj(n), subtreeSize(n, 1), heavyChild(n, -1),
chainHead(n), parent(n, -1), depth(n, 0) {}
void addEdge(int u, int v) { adj[u].push_back(v); adj[v].push_back(u); }
// First DFS: compute subtree sizes and identify each node's heavy child.
void dfsSize(int u, int p, int d) {
parent[u] = p; depth[u] = d;
int maxSubtree = 0;
for (int v : adj[u]) {
if (v == p) continue;
dfsSize(v, u, d + 1);
subtreeSize[u] += subtreeSize[v];
if (subtreeSize[v] > maxSubtree) { // track the child with the LARGEST subtree
maxSubtree = subtreeSize[v];
heavyChild[u] = v; // that's the heavy child β same chain continues through it
}
}
}
// Second DFS: assign each node to a chain, identified by that chain's topmost node.
void dfsChain(int u, int head) {
chainHead[u] = head;
if (heavyChild[u] != -1) {
dfsChain(heavyChild[u], head); // heavy child continues the SAME chain
}
for (int v : adj[u]) {
if (v != parent[u] && v != heavyChild[u]) {
dfsChain(v, v); // light child STARTS a new chain (headed by itself)
}
}
}
void build(int root) {
dfsSize(root, -1, 0);
dfsChain(root, root);
}
// A full path-query implementation would additionally assign each node a position in a
// flattened array (via the chain traversal order) and build a Segment Tree over that array β
// then answer path(u,v) queries by repeatedly jumping "up to the current chain's head,"
// querying that chain's Segment-Tree range, and moving to the parent chain, until u and v
// are on the same chain β giving the O(log^2 n) bound derived in section 4.
};
// Example usage
int main() {
std::vector<int> arr = {3, 34, 4, 12, 5, 2};
std::cout << "Subset summing to 9 exists? " << subsetSumExists(arr, 9) << "\n"; // 1 (true)
std::cout << "Subset summing to 100 exists? " << subsetSumExists(arr, 100) << "\n"; // 0 (false)
HLD hld(7);
hld.addEdge(0, 1); hld.addEdge(0, 2); // 1-indexed tree from section 3(b), 0-indexed here
hld.addEdge(1, 3); hld.addEdge(1, 4);
hld.addEdge(2, 5);
hld.addEdge(3, 6);
hld.build(0);
std::cout << "Chain heads: ";
for (int i = 0; i < 7; ++i) std::cout << hld.chainHead[i] << " ";
std::cout << "\n"; // node 6 and node 3 should share the same chain head as node 0
return 0;
}
9. Code Walkthrough
generateSumsβs mask-based subset enumeration: Identical technique to Bitmask DP (Chapter 17) β every integer from 0 to2^count - 1represents one possible subset of thecountelements in this half, with bitiindicating βelementiis included.βsubsetSumExistsβs sort-one-half, binary-search-the-other structure: This is the βcombineβ stepβs concrete implementation β sortingsumsBonce (O(2^(n/2) log(2^(n/2)))) enables each ofsumsAβs2^(n/2)elements to be checked viastd::binary_search(Chapter 1βs technique, reused verbatim from the standard library) in O(log(2^(n/2))) each, rather than a naive O(2^(n/2)) linear scan per check.HLD::dfsSizeβs heavy-child tracking: A straightforward post-order-style computation (compute all childrenβs subtree sizes first, then sum them for the current node) β directly analogous to Tree Diameterβs height computation (Chapter 15) β with the added bookkeeping of remembering which specific child had the largest subtree.HLD::dfsChainβs asymmetric recursive calls: The heavy child recursion (dfsChain(heavyChild[u], head)) passes the SAMEheadvalue forward, extending the current chain; every other (light) child recursion (dfsChain(v, v)) starts a brand new chain headed by itself β this asymmetry is the entire mechanism by which heavy chains extend maximally while light edges always begin fresh chains.- Why the full path-query logic is only described, not implemented: as the comment notes, a complete HLD implementation additionally requires flattening the tree into an array (via chain-traversal order) and layering a Segment Tree (Data Structures guide, Ch. 15) on top β genuinely substantial additional code that would roughly double this chapterβs length; the chain-decomposition logic shown here is the conceptual core that the rest builds upon.
Common mistakes to watch for here:
- In Meet in the Middle, forgetting to sort one of the two halves before binary-searching into it β
std::binary_searchrequires sorted input, and skipping this step silently produces incorrect (or crashing) results. - In HLD, computing
dfsSizeanddfsChainin the wrong order (chain assignment genuinely requires subtree sizes to already be known) β always run the size-computation DFS fully before the chain-assignment DFS. - Assuming a small example (like the 6-element Meet in the Middle demo) reflects the techniqueβs real value β always mentally rescale to nβ40 to appreciate why this technique matters in practice.
10. Dry Run
subsetSumExists([3,34,4,12,5,2], target=9), matching section 3(a)βs trace: half A = [3,34,4] generates sums {0,3,34,4,37,7,38,41}; half B = [12,5,2] generates sums {0,12,5,2,17,14,7,19}, sorted to [0,2,5,7,12,14,17,19]. Checking each A-sum against target - A-sum in sorted B: when A-sum=4, needed = 9-4 = 5, and 5 IS present in the sorted B-sums array (binary search finds it) β returns true, confirming the subset {4} βͺ {5} = {4,5} sums to 9. β
11. Complexity Table
| Technique | Time | Space | Practical limit |
|---|---|---|---|
| Meet in the Middle | O(2^(n/2) Β· n) | O(2^(n/2)) | n β² 35-40 |
| Heavy-Light Decomposition (build) | O(n) | O(n) | No practical limit beyond tree size |
| HLD (per path query, with Segment Tree) | O(logΒ² n) | β | β |
Every entry explained: Meet in the Middleβs complexity is dominated by generating and sorting 2^(n/2)-sized lists β still exponential, but with a dramatically smaller exponent than brute forceβs 2βΏ, extending the practical n range roughly 15-20 further than Bitmask DP alone. HLDβs build cost is a straightforward O(n) (two linear DFS passes); its real payoff is the O(logΒ² n) per-query cost once built, which is what makes it valuable for workloads with many repeated path queries on a large, static (or update-tolerant) tree.
12. Common Mistakes
- Applying Meet in the Middle when n is small enough for simpler techniques (Bitmask DP, or even brute force) β added complexity with no real benefit for small n; reserve this technique for the specific ~25-40 range where itβs genuinely necessary.
- Forgetting to sort before binary search in the Meet in the Middle combine step.
- Computing HLDβs chain assignment before subtree sizes are known β the two DFS passes have a strict dependency order.
- Underestimating HLDβs implementation complexity β attempting to write it under interview time pressure without extensive prior practice is usually not realistic; this technique is much more of a βknow it exists and can describe the approachβ item for most software engineering contexts, genuinely implemented from scratch mainly in competitive programming.
- Confusing HLDβs O(logΒ² n) with a simpler O(log n) β the squared term comes from the combination of βO(log n) chains crossedβ AND βO(log n) per chainβs Segment Tree query,β a detail worth being precise about.
13. Interview Questions
Conceptual:
- Why does splitting a problem exactly in half (rather than any other ratio) minimize Meet in the Middleβs total work?
- Whatβs the maximum possible n for Meet in the Middle to remain practical, and how does this compare to Bitmask DPβs limit?
- Explain why any root-to-node path in a tree crosses at most O(log n) light edges under Heavy-Light Decomposition.
- Why does HLDβs per-query complexity have a squared log factor (O(logΒ² n)) rather than a single log factor?
- In what real-world context does βmeet in the middleβ as an algorithmic technique share its name with an actual named cryptographic attack?
Coding:
- Implement Meet in the Middle for the Subset Sum problem (as shown above).
- Closest Subset Sum to a target, using Meet in the Middle (a natural extension beyond exact-match subset sum).
- Implement HLDβs chain-decomposition logic (the skeleton shown above) and verify chain assignments on a hand-built test tree.
- (Advanced, optional) Extend the HLD skeleton with Euler-tour flattening and Segment Tree integration for full path-sum queries.
Follow-ups / interviewer traps:
- βYour Meet in the Middle solution works for n=30 β what about n=50?β (tests recognizing the techniqueβs own practical limit β at n=50,
2^25is still large but borderline; beyond that, neither Meet in the Middle nor Bitmask DP suffices, and the interviewer is testing whether the candidate over-claims a techniqueβs applicability) - βWhen would you use HLD instead of just recomputing the tree DP (Chapter 17) for each query?β (tests understanding that Chapter 17βs tree DP computes ONE global answer via one traversal, while HLD is built specifically for MANY repeated ARBITRARY-PATH queries β genuinely different problem shapes)
- βIs Heavy-Light Decomposition something youβd expect to implement in a 45-minute interview?β (a fair, honest answer is no β this is a multi-hour competitive-programming-tier technique, and recognizing that boundary is itself a sign of mature engineering judgment)
14. Practice Problems
Medium
- Partition Equal Subset Sum (LeetCode 416) β solvable via DP (Ch.13) for small sums, or Meet in the Middle for large value ranges with small n
Hard
- Closest Subsequence Sum (LeetCode 1755) β a direct Meet in the Middle application
- Path Queries on Trees (various competitive programming judges β Codeforces, AtCoder β tagged
HLDorheavy-light decomposition)
Also recommended: Codeforces problems tagged meet-in-the-middle (rating 1900-2300) and dsu on tree / hld (rating 2200+) for competitive-programming-depth practice; for standard interview preparation, understanding the concepts here (and being able to describe them clearly) is typically sufficient β full from-scratch HLD implementation is a specialized, advanced skill beyond most standard interview loops.
15. Summary
Key takeaways:
- Meet in the Middle extends exact exponential search roughly 15-20 further in practical n by splitting the problem, solving each half independently, and combining via sort + binary search β still exponential, but with a dramatically better exponent.
- Heavy-Light Decomposition provides a provable O(log n)-chains-per-path guarantee for ANY tree shape, enabling O(logΒ² n) path queries by combining tree decomposition with a Segment Tree β a genuinely elegant structural result, though substantial to implement fully.
- Both techniques exemplify this entire guideβs recurring throughline: when a direct approach is too slow, look for a way to split the problem into independently-solvable pieces that combine efficiently β the same spirit as Merge Sort (Ch.3), Prefix Sum (Ch.9), and DP itself (Ch.12-13), now applied to genuinely harder problem shapes.
Complexity recap:
| Time | Practical limit | |
|---|---|---|
| Meet in the Middle | O(2^(n/2) Β· n) | n β² 35-40 |
| HLD (build / per-query) | O(n) / O(logΒ² n) | Tree size |
Decision guide: Reach for Meet in the Middle when Bitmask DPβs 2βΏ is too slow but the problem is still fundamentally exponential/subset-based, and n is in the ~25-40 range. Reach for Heavy-Light Decomposition when you need many repeated arbitrary-path queries (not just one global tree-wide answer) on a large tree, and O(n)-per-query is too slow. For most standard software engineering interviews, understanding when and why each technique applies is the realistic, valuable target β full from-scratch implementation under time pressure is squarely competitive-programming territory.
The Algorithms Handbook β Truly Complete
This closes out every category from the original roadmap, including the βAdvanced Algorithmsβ leaf that Chapter 0βs prerequisite tree always pointed toward: Complexity Analysis β Binary Search β Sorting β Two Pointer/Sliding Window/Prefix Sum β Greedy β Backtracking β Dynamic Programming (Fundamentals, Classic Problems, and now Bitmask/Tree DP) β Graph Algorithms β Tree Algorithms β String Algorithms β Meet in the Middle & Heavy-Light Decomposition.
Combined with its companion Data Structures guide, these two handbooks now form a complete, self-consistent curriculum β from the first array index to the most advanced tree-decomposition techniques β with every chapter cross-referencing exactly where it builds on something already covered, and exactly where a harder extension awaits if you want to go further.
Data Structures Mastery Guide
How This Guide Is Organized
This is a multi-file textbook. Because doing every data structure justice (theory, internal working, complexities with why, C++ implementation, dry run, interview questions, practice problems) takes real space, each data structure gets its own chapter file. This file is the spine of the whole guide β the roadmap, the βwhich structure do I pickβ decision engine, and the comparison tables youβll come back to again and again.
Complete table of contents (all chapters delivered):
00_roadmap_and_strategy.mdβ you are here01_arrays.md02_strings.md03_linked_lists.md04_stack_and_queue.md05_heaps.md06_hash_tables.md07_binary_tree_and_bst.md08_avl_tree.md09_trie.md10_btree_overview.md11_graphs_part1_bfs_dfs.md12_topological_sort.md13_minimum_spanning_tree.md14_shortest_path.md15_segment_tree.md16_fenwick_tree.md17_disjoint_set_union.md18_skip_list.md19_bloom_filter.md20_lru_cache.mdβ capstone
Part 1 β The Learning Roadmap
Prerequisites
β
βββ Programming Fundamentals (variables, functions, pointers/references, memory model)
βββ Big-O Analysis (time & space complexity, best/avg/worst case, amortized analysis)
βββ Recursion (call stack, base case, recurrence relations)
β
βββ Linear Data Structures
β βββ Array β foundation for everything; contiguous memory
β βββ String β array of chars + pattern algorithms
β βββ Linked List β breaks the "contiguous" assumption
β βββ Stack β LIFO discipline on top of array/list
β βββ Queue β FIFO discipline on top of array/list
β
βββ Hash-Based Structures
β βββ Hash Table β O(1) average lookup, needs arrays + linked lists (chaining)
β βββ Hash Map β key-value variant
β βββ Hash Set β key-only variant
β
βββ Trees
β βββ Binary Tree β hierarchical data, needs recursion mastery
β βββ BST β ordered binary tree, enables O(log n) search
β βββ AVL Tree β self-balancing BST, guarantees O(log n)
β βββ Heap β priority-ordered complete binary tree
β βββ Trie β prefix tree, specialized for strings
β βββ B-Tree (Overview) β disk-optimized generalization of BST
β
βββ Graphs
β βββ Representation (adjacency list/matrix) β needs arrays + linked lists + hash maps
β βββ BFS β needs Queue
β βββ DFS β needs Stack/recursion
β βββ Topological Sort β needs DFS + graph theory (DAGs)
β βββ MST (Kruskal/Prim) β needs DSU + Heap
β βββ Shortest Path (Dijkstra/Bellman-Ford) β needs Heap + Queue
β
βββ Advanced Data Structures
βββ Segment Tree β needs Binary Tree + recursion, for range queries
βββ Fenwick Tree (BIT) β needs bit manipulation, lighter alternative to Segment Tree
βββ Disjoint Set Union β needs arrays, for connectivity/MST
βββ Skip List β needs Linked List, probabilistic alternative to balanced trees
βββ Bloom Filter (Overview) β needs Hashing, probabilistic set membership
βββ LRU Cache β needs Hash Map + Doubly Linked List (capstone project)
Why this order?
| Stage | Why it comes here | Prerequisites | Learning Outcome |
|---|---|---|---|
| Big-O & Recursion | You cannot reason about any data structureβs cost without Big-O, and trees/graphs are naturally recursive | Basic programming | Ability to analyze any algorithmβs cost and trace recursive calls |
| Linear structures | Simplest memory models; every later structure is built from these primitives | Big-O, Recursion | Understand contiguous vs. linked memory, LIFO/FIFO discipline |
| Hashing | Needs arrays (buckets) + linked lists (collision chains) already understood | Arrays, Linked Lists | Understand amortized O(1) and hash collision handling |
| Trees | Needs recursion fluency; introduces hierarchical (non-linear) thinking | Recursion, Linked Lists | Understand branching structures, balancing, ordered traversal |
| Graphs | Generalizes trees (cycles allowed, no root); needs Queue/Stack/Heap from earlier | Trees, Stack, Queue, Hashing | Model real-world networks; traversal and optimization algorithms |
| Advanced structures | Composed from everything above to solve specialized problems (range queries, connectivity, caching) | Trees, Arrays, Hashing, DSU concepts | Solve competitive-programming-level and system-design-level problems |
Suggested Timeline (self-paced, ~10-12 weeks at 1-2 hrs/day)
| Week | Focus | Mini Project |
|---|---|---|
| 1 | Big-O, Recursion, Arrays, Strings | Implement dynamic array (vector) from scratch |
| 2 | Linked List (singly, doubly, circular) | Implement a text editorβs undo feature with a linked list |
| 3 | Stack & Queue | Balanced parentheses checker; browser history simulator |
| 4 | Hash Table / Map / Set | Build your own HashMap with chaining + resizing |
| 5 | Binary Tree, BST | In-order/pre/post traversal visualizer |
| 6 | AVL Tree, Heap | Build a priority-based task scheduler |
| 7 | Trie, B-Tree overview | Autocomplete system |
| 8 | Graph representation, BFS, DFS | Maze solver |
| 9 | Topological Sort, MST, Shortest Path | Course scheduler; network cost optimizer |
| 10 | Segment Tree, Fenwick Tree, DSU | Range-sum query system; Kruskalβs MST with DSU |
| 11 | Skip List, Bloom Filter | Probabilistic membership tester |
| 12 | LRU Cache (capstone) + full mock interviews | Production-grade LRU cache with O(1) ops |
Part 3 β Comparison Tables
Array vs Linked List
| Aspect | Array | Linked List |
|---|---|---|
| Memory layout | Contiguous | Scattered, linked via pointers |
| Access by index | O(1) | O(n) |
| Insert/Delete at front | O(n) (shift elements) | O(1) |
| Insert/Delete at end | O(1) amortized (dynamic array) | O(1) if tail pointer kept |
| Insert/Delete in middle | O(n) | O(n) to find + O(1) to link |
| Memory overhead | Low (just data) | Higher (data + pointer(s)) |
| Cache performance | Excellent (locality) | Poor (pointer chasing) |
| Use case | Random access, fixed/known size ranges | Frequent insert/delete, unknown size |
Stack vs Queue
| Aspect | Stack | Queue |
|---|---|---|
| Discipline | LIFO (Last In, First Out) | FIFO (First In, First Out) |
| Core ops | push, pop, peek | enqueue, dequeue, front |
| Typical backing structure | Array or Linked List | Array (circular) or Linked List |
| Real use | Function call stack, undo, backtracking | Task scheduling, BFS, print queue |
Queue vs Deque
| Aspect | Queue | Deque (Double-Ended Queue) |
|---|---|---|
| Insertion/removal points | Rear (in), Front (out) only | Both ends |
| Flexibility | Lower | Higher β can act as stack or queue |
| Use case | Simple FIFO tasks | Sliding window problems, palindrome checks |
Hash Table vs Tree (BST)
| Aspect | Hash Table | BST |
|---|---|---|
| Average search/insert/delete | O(1) | O(log n) |
| Worst case | O(n) (bad hash/collisions) | O(n) (unbalanced) |
| Ordering | No inherent order | Sorted order maintained |
| Range queries | Not supported directly | Supported efficiently |
| Memory overhead | Moderate (buckets + collision handling) | Moderate (pointers per node) |
| Use case | Fast lookup, no ordering needed | Sorted data, range queries |
BST vs AVL vs Red-Black Tree
| Aspect | BST | AVL Tree | Red-Black Tree |
|---|---|---|---|
| Balance guarantee | None | Strict (height diff β€ 1) | Loose (path length β€ 2Γ shortest) |
| Search | O(log n) avg, O(n) worst | O(log n) guaranteed | O(log n) guaranteed |
| Insert/Delete | O(log n) avg, O(n) worst | O(log n) but more rotations | O(log n), fewer rotations |
| Rotation frequency | N/A | High (strict balance) | Lower |
| Use case | Simple, small/random data | Read-heavy workloads | Write-heavy workloads (e.g., Linux CFS, std::map) |
Heap vs BST
| Aspect | Heap | BST |
|---|---|---|
| Structure | Complete binary tree (array-backed) | Not necessarily complete |
| Ordering | Parent β€/β₯ children only (weak order) | Left < Root < Right (strict order) |
| Find min/max | O(1) | O(log n) (leftmost/rightmost) |
| Find arbitrary element | O(n) | O(log n) |
| Use case | Priority queues, scheduling | Sorted traversal, range search |
Trie vs Hash Map
| Aspect | Trie | Hash Map |
|---|---|---|
| Key type | Strings (sequences) | Any hashable type |
| Prefix search | O(L) β excellent | Not supported directly |
| Memory | Higher (node per character) | Lower typically |
| Ordered iteration | Lexicographic, natural | Not ordered |
| Use case | Autocomplete, spell-check, IP routing | General key-value lookup |
BFS vs DFS
| Aspect | BFS | DFS |
|---|---|---|
| Data structure used | Queue | Stack (or recursion) |
| Explores | Level by level | Branch by branch, deep first |
| Shortest path (unweighted) | Yes | No (not guaranteed) |
| Memory usage | Can be high (wide graphs) | Can be high (deep graphs) |
| Use case | Shortest path, level-order, social network βdegrees of separationβ | Cycle detection, topological sort, connected components |
Segment Tree vs Fenwick Tree (BIT)
| Aspect | Segment Tree | Fenwick Tree |
|---|---|---|
| Build time | O(n) | O(n log n) or O(n) with tricks |
| Query/Update | O(log n) | O(log n) |
| Memory | ~4n | ~n |
| Flexibility | Supports range min/max/gcd/custom ops | Best suited for prefix sums/frequency |
| Code complexity | Higher | Lower, simpler to implement |
| Use case | Complex range queries with updates | Simple prefix-sum / frequency-count problems |
Part 4 β Decision Guide: βWhich Data Structure Should I Choose?β
START: What is your primary need?
β
βββ Need fast lookup by key, don't care about order?
β βββ Hash Map / Hash Set β O(1) average
β
βββ Need data kept in sorted order AND fast lookup?
β βββ Frequent reads, few writes β AVL Tree
β βββ Frequent writes β Red-Black Tree (or std::map in practice)
β
βββ Need to repeatedly get the min/max element (priority)?
β βββ Heap (Priority Queue) β O(log n) insert/extract-min
β
βββ Need prefix-based search (autocomplete, dictionary)?
β βββ Trie
β
βββ Need to process elements in the order they arrived?
β βββ Queue (FIFO)
β
βββ Need to undo actions / match nested structures (parentheses, recursion)?
β βββ Stack (LIFO)
β
βββ Need frequent insert/delete at arbitrary positions, size changes a lot?
β βββ Linked List (Doubly Linked if you need backward traversal)
β
βββ Need random access by index, size relatively fixed?
β βββ Array / Dynamic Array (Vector)
β
βββ Modeling relationships/connections (networks, maps, dependencies)?
β βββ Need shortest path (unweighted) β BFS
β βββ Need shortest path (weighted, non-negative) β Dijkstra (Heap-based)
β βββ Need shortest path (negative weights allowed) β Bellman-Ford
β βββ Need to detect cycles / order tasks by dependency β DFS + Topological Sort
β βββ Need minimum connections to link everything β MST (Kruskal + DSU, or Prim + Heap)
β
βββ Need to answer "sum/min/max of range [L,R]" repeatedly, with updates?
β βββ Simple prefix sums, point updates β Fenwick Tree (BIT)
β βββ Complex range queries (min, gcd, lazy propagation) β Segment Tree
β
βββ Need to quickly check "are these two elements connected/grouped"?
β βββ Disjoint Set Union (Union-Find)
β
βββ Need probabilistic "have I seen this before" with minimal memory, false positives OK?
β βββ Bloom Filter
β
βββ Need a cache that evicts least-recently-used items in O(1)?
βββ LRU Cache (Hash Map + Doubly Linked List)
Reasoning behind key decisions:
- Hash Map over BST for pure lookup: if you never need sorted order or range queries, paying O(log n) instead of O(1) is wasted cost.
- Heap over sorted array for priority queues: maintaining a fully sorted array costs O(n) per insert; a heap only costs O(log n) because it only enforces partial order.
- Fenwick Tree over Segment Tree when possible: simpler code, less memory β reach for Segment Tree only when you need operations Fenwick canβt express cleanly (range min/max, complex merges, lazy propagation).
- DSU over BFS/DFS for connectivity queries: if you need repeated βare A and B connectedβ queries with a changing graph (edges added over time), DSU answers in near O(1) amortized; recomputing BFS/DFS each time would be far more expensive.
Part 6 β Master Cheat Sheet (Complexity Recap)
| Structure | Access | Search | Insert | Delete | Space |
|---|---|---|---|---|---|
| Array | O(1) | O(n) | O(n) | O(n) | O(n) |
| Dynamic Array | O(1) | O(n) | O(1) amortized | O(n) | O(n) |
| Singly Linked List | O(n) | O(n) | O(1)* | O(1)* | O(n) |
| Doubly Linked List | O(n) | O(n) | O(1)* | O(1)* | O(n) |
| Stack | O(n) | O(n) | O(1) | O(1) | O(n) |
| Queue | O(n) | O(n) | O(1) | O(1) | O(n) |
| Hash Table (avg) | β | O(1) | O(1) | O(1) | O(n) |
| Hash Table (worst) | β | O(n) | O(n) | O(n) | O(n) |
| BST (avg) | O(log n) | O(log n) | O(log n) | O(log n) | O(n) |
| BST (worst) | O(n) | O(n) | O(n) | O(n) | O(n) |
| AVL Tree | O(log n) | O(log n) | O(log n) | O(log n) | O(n) |
| Heap | O(1) min/max | O(n) | O(log n) | O(log n) | O(n) |
| Trie | β | O(L) | O(L) | O(L) | O(alphabet Γ nodes) |
| Segment Tree | β | O(log n) | O(log n) | O(log n) | O(n) |
| Fenwick Tree | β | O(log n) | O(log n) | O(log n) | O(n) |
| DSU (with path compression + union by rank) | β | ~O(Ξ±(n)) | ~O(Ξ±(n)) | β | O(n) |
*with pointer to node already in hand; O(n) if you must search first.
Memory tricks:
- βArray = fast read, slow write in the middle.β βLinked List = slow read, fast write anywhere (once located).β
- βHeap gives you the best item fast, not any item fast.β
- βBST is sorted array + fast insert, at the cost of possible imbalance.β
- βTrie trades memory for prefix-speed.β
- βDSU: think of it as
Ξ±(n)β constant for all practical n β thatβs why Union-Find is called βalmost O(1)β.β
Interview Readiness Checklist (fill in as you complete each chapter)
- Arrays β implemented dynamic array, solved 10+ problems
- Strings β pattern matching (KMP/Z-function), solved 10+ problems
- Linked Lists β reversal, cycle detection, merge, solved 10+ problems
- Stack/Queue β monotonic stack, sliding window max, solved 10+ problems
- Hashing β collision handling explained, solved 10+ problems
- Trees β all traversals, balancing explained, solved 10+ problems
- Heap β build-heap in O(n) explained, solved 10+ problems
- Trie β autocomplete built, solved 5+ problems
- Graphs β BFS/DFS/topo sort/MST/shortest path all implemented, solved 15+ problems
- Advanced β Segment Tree, Fenwick, DSU implemented, solved 10+ problems
- Capstone β LRU Cache built and can explain O(1) design in an interview
Next up: open 01_arrays.md for the full 15-section deep-dive chapter on Arrays, built to the exact template weβll repeat for every remaining structure. Tell me which structure you want next (String, Linked List, Stack/Queue, Hash Table, Trees, Graphs, or Advanced) and Iβll build it to this same depth.
Chapter 1: Arrays
Study time: ~4-6 hours | Prerequisite: Big-O basics | Difficulty: Beginner
1. Introduction
Definition: An array is a collection of elements of the same type, stored in contiguous memory locations, accessed by an integer index.
Purpose: To store multiple values under one variable name while allowing O(1) direct access to any element via its position.
Real-world analogy: Think of a row of numbered mailboxes on a street. If you know a boxβs number (index), you walk straight to it β you donβt check every box before it. Thatβs what makes array access O(1): the address of box i is simply base_address + i * size_of_one_box.
Motivation: Before arrays, programs stored related data in separate named variables (score1, score2, score3β¦). This doesnβt scale β you canβt loop over βscore1 through score1000β without an indexable structure.
History: Arrays are as old as computing itself β they map directly onto how RAM is physically addressed (a flat sequence of byte addresses), making them the most βnativeβ data structure a computer understands.
2. Why Do We Need It?
Problem it solves: Grouping related data and accessing any element in constant time without traversal.
Why simpler alternatives fail: Using individual variables means you canβt parameterize access (get element number i becomes impossible without an if-else chain), and you canβt easily pass βall the dataβ to a function.
Trade-offs:
- You gain O(1) random access and excellent cache locality (data sits next to each other in memory, which CPUs love).
- You pay for it with expensive insertion/deletion in the middle (everything after must shift) and, for static arrays, a fixed size decided upfront.
This trade-off β fast reads, slow structural changes β is the first and most important trade-off youβll see repeated (in different forms) throughout this entire guide.
3. Internal Working
A static array of 5 integers in memory looks like this:
Index: 0 1 2 3 4
+-----+-----+-----+-----+-----+
Value: | 10 | 22 | 5 | 47 | 8 |
+-----+-----+-----+-----+-----+
Address: 1000 1004 1008 1012 1016 (assuming 4-byte ints)
Address calculation (why access is O(1)):
address(i) = base_address + i * element_size
address(3) = 1000 + 3 * 4 = 1012 β directly computed, no traversal needed
Dynamic array (e.g., std::vector) growth, which is what makes amortized O(1) append possible:
Capacity 4, size 4: [A][B][C][D] β full, next push_back triggers growth
Step 1: Allocate new block of double capacity (8)
[ ][ ][ ][ ][ ][ ][ ][ ]
Step 2: Copy old elements over
[A][B][C][D][ ][ ][ ][ ]
Step 3: Free old block, insert new element
[A][B][C][D][E][ ][ ][ ] β size 5, capacity 8
Because capacity doubles each time, the total copying cost across n insertions sums to O(n), which spread over n operations gives O(1) amortized per insertion β even though any single insertion that triggers a resize costs O(n).
4. Operations
Insert
- At the end (dynamic array, capacity available): Place at
size, increment size. O(1). - At the end (capacity full): Trigger resize (see above), then insert. O(n) worst case, O(1) amortized.
- At index i: Shift all elements from i to end one position right, then place. O(n).
- Edge case: inserting at index 0 is the worst case (shifts everything); inserting at
sizeis the best case.
Delete
- From the end: Decrement size. O(1).
- At index i: Shift all elements after i one position left to close the gap. O(n).
- Edge case: deleting from an empty array must be guarded against (underflow).
Update
arr[i] = valueβ direct address computation. O(1).
Search
- Unsorted: Linear scan, O(n).
- Sorted: Binary search, O(log n) β only possible because arrays support O(1) random access, which is what lets binary search jump to the middle instantly.
Traverse
- Visit each element once, O(n). Cache-friendly because of contiguous memory (sequential memory access is much faster than random access on real hardware due to CPU cache lines and prefetching).
Peek
- Look at first/last element without removing: O(1) if you track size.
5. Time & Space Complexity
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Access by index | O(1) | O(1) |
| Search (unsorted) | O(n) | O(1) |
| Search (sorted, binary search) | O(log n) | O(1) |
| Insert at end (dynamic array) | O(1) amortized | O(1) extra (occasionally O(n) during resize) |
| Insert at beginning/middle | O(n) | O(1) extra |
| Delete at end | O(1) | O(1) |
| Delete at beginning/middle | O(n) | O(1) extra |
| Overall storage | β | O(n) |
Why these hold:
- Access is O(1) because the address formula is a single multiplication + addition β no dependency on array size.
- Insert/delete at arbitrary position is O(n) because, on average, half the elements must shift to preserve contiguity β there is no way around this without abandoning the βcontiguous memoryβ property (which is exactly what a Linked List does instead).
- Amortized O(1) append comes from the geometric doubling strategy: the sum of a geometric series (1+2+4+β¦+n) is O(n), spread across n insertions = O(1) each on average.
6. Advantages
- O(1) random access by index.
- Excellent cache locality β fast in practice, not just in theory.
- Simple, low memory overhead (no pointers needed per element).
- Predictable memory layout, easy to reason about and debug.
7. Disadvantages
- Fixed size for static arrays (must know size upfront, or pay for resizing).
- Expensive insert/delete in the middle or at the front β O(n).
- Wasted space if over-allocated, or costly reallocation if under-allocated.
- Not ideal when the structure changes shape frequently.
8. Real-World Applications
- Operating Systems: Process tables, page tables β indexed lookup of fixed-size records.
- Databases: Columnar storage engines use arrays for contiguous column data (cache-friendly scans).
- Browsers: The DOMβs
NodeList, image pixel buffers (a 2D array of pixel values). - Search Engines: Inverted index postings lists are often stored as sorted arrays for fast intersection.
- Game Development: Grids/tilemaps, entity component arrays (Data-Oriented Design relies heavily on arrays for cache performance).
- Networking: Packet buffers are fixed-size byte arrays.
- Compilers: Symbol tables and instruction arrays (bytecode arrays in VMs).
- AI/ML: Tensors (the core data structure of ML frameworks like NumPy/PyTorch) are fundamentally multi-dimensional arrays optimized for contiguous, vectorized access.
Arrays show up everywhere real performance matters, because CPUs are physically optimized for sequential memory access.
9. Implementation (C++17)
#include <iostream>
#include <stdexcept>
#include <algorithm>
// A minimal dynamic array implementation, similar in spirit to std::vector.
// Demonstrates manual memory management, resizing, and amortized O(1) append.
class DynamicArray {
private:
int* data; // pointer to heap-allocated block
size_t sz; // current number of elements
size_t cap; // current allocated capacity
// Doubles capacity and copies existing elements into the new block.
void resize(size_t newCapacity) {
int* newData = new int[newCapacity];
for (size_t i = 0; i < sz; ++i) {
newData[i] = data[i]; // copy old elements
}
delete[] data; // free old memory
data = newData;
cap = newCapacity;
}
public:
// Constructor: start with small capacity to demonstrate growth behavior.
DynamicArray() : data(new int[1]), sz(0), cap(1) {}
// Destructor: release heap memory to avoid leaks.
~DynamicArray() {
delete[] data;
}
// Insert at the end. Amortized O(1).
void push_back(int value) {
if (sz == cap) {
resize(cap * 2); // double capacity when full
}
data[sz] = value;
sz++;
}
// Remove last element. O(1).
void pop_back() {
if (sz == 0) throw std::underflow_error("pop_back on empty array");
sz--;
}
// Insert at arbitrary index. O(n) due to shifting.
void insert_at(size_t index, int value) {
if (index > sz) throw std::out_of_range("insert index out of range");
if (sz == cap) resize(cap * 2);
for (size_t i = sz; i > index; --i) {
data[i] = data[i - 1]; // shift elements right
}
data[index] = value;
sz++;
}
// Delete at arbitrary index. O(n) due to shifting.
void delete_at(size_t index) {
if (index >= sz) throw std::out_of_range("delete index out of range");
for (size_t i = index; i < sz - 1; ++i) {
data[i] = data[i + 1]; // shift elements left
}
sz--;
}
// Access by index. O(1). Bounds-checked for safety.
int& operator[](size_t index) {
if (index >= sz) throw std::out_of_range("index out of range");
return data[index];
}
// Linear search. O(n).
int find(int value) const {
for (size_t i = 0; i < sz; ++i) {
if (data[i] == value) return static_cast<int>(i);
}
return -1; // not found
}
size_t size() const { return sz; }
size_t capacity() const { return cap; }
bool empty() const { return sz == 0; }
void print() const {
std::cout << "[ ";
for (size_t i = 0; i < sz; ++i) std::cout << data[i] << " ";
std::cout << "] (size=" << sz << ", capacity=" << cap << ")\n";
}
};
// Example usage
int main() {
DynamicArray arr;
arr.push_back(10);
arr.push_back(20);
arr.push_back(30);
arr.print(); // [ 10 20 30 ] (size=3, capacity=4)
arr.insert_at(1, 15);
arr.print(); // [ 10 15 20 30 ] (size=4, capacity=4)
arr.delete_at(2);
arr.print(); // [ 10 15 30 ] (size=3, capacity=4)
std::cout << "Index of 30: " << arr.find(30) << "\n"; // 2
return 0;
}
10. Code Walkthrough
data(int*): A raw pointer to a contiguous heap block. This is the actual βarrayβ β everything else is bookkeeping around it.szvscap:szis how many slots are used;capis how many slots exist. This distinction is what makes amortized growth possible β we over-allocate so future pushes donβt always need a new allocation.resize(): Allocates a new, larger block, copies every element over (O(n)), then frees the old block. This is the expensive operation that happens rarely (only whensz == cap), which is why its cost βamortizes awayβ across many cheap O(1) pushes.push_back: Checks capacity first. This ordering (check-then-write) is a common pattern β always validate before mutating.insert_at/delete_at: The shifting loops are the heart of why these are O(n). Note the direction of shifting: insert shifts right-to-left (to avoid overwriting data you still need to move), delete shifts left-to-right. Getting this direction backwards is a classic bug that silently corrupts data.operator[]with bounds checking: Realstd::vector::operator[]does not bounds-check (for performance) β thatβs what.at()is for. Here we bounds-check for teaching safety.- Destructor: Without
delete[] data, everyDynamicArraywould leak its heap block β a classic C++ memory-management mistake covered in section 14.
Common mistakes to watch for here:
- Off-by-one errors in loop bounds (
i <= szinstead ofi < sz). - Forgetting to check
sz == capbefore writing, causing a buffer overflow. - Shifting in the wrong direction during insert/delete, corrupting adjacent data.
11. Dry Run
Input: push_back(10), push_back(20), push_back(30), insert_at(1, 15), delete_at(2)
| Step | Operation | State (cap in parens) | Notes |
|---|---|---|---|
| 0 | init | [] (cap 1) | sz=0 |
| 1 | push_back(10) | [10] (cap 1) | sz=1, fits exactly |
| 2 | push_back(20) | sz==cap(1) β resize to 2 β [10,20] (cap 2) | resize triggered |
| 3 | push_back(30) | sz==cap(2) β resize to 4 β [10,20,30] (cap 4) | resize triggered |
| 4 | insert_at(1,15) | shift index 2β3 (30), index1β2(20); place 15 at index1 β [10,15,20,30] (cap 4) | sz=4, cap full but exactly fits |
| 5 | delete_at(2) | shift index3β2(30) left β [10,15,30] (cap 4, sz=3) | element β20β overwritten and logically removed |
Final array: [10, 15, 30], size 3, capacity 4.
12. Interview Questions
Conceptual:
- Why is array access O(1) but linked list access O(n)?
- Explain amortized time complexity using dynamic array
push_backas an example. - Why does
std::vectortypically grow by doubling rather than adding a fixed amount each time? - Whatβs the difference between a static array and a dynamic array?
- Why is inserting at the front of an array worse than inserting at the back?
Coding:
- Reverse an array in-place.
- Find the maximum subarray sum (Kadaneβs Algorithm).
- Rotate an array by k positions in-place.
- Find the missing number in an array of 1..n.
- Merge two sorted arrays in-place.
- Move all zeros to the end while maintaining relative order.
- Find the two numbers that sum to a target (Two Sum).
Follow-ups / interviewer traps:
- βCan you do it without extra space?β (tests in-place manipulation skill)
- βWhat if the array is sorted β can you do better than O(n)?β (tests binary search intuition)
- βWhat if there are duplicates?β (tests edge-case handling)
- After Two Sum: βWhat if the array is sorted?β β expects two-pointer O(n) instead of hash map O(n) with O(n) space.
13. Practice Problems
Easy
- Two Sum (LeetCode 1)
- Remove Duplicates from Sorted Array (LeetCode 26)
- Best Time to Buy and Sell Stock (LeetCode 121)
- Move Zeroes (LeetCode 283)
Medium
- Rotate Array (LeetCode 189)
- Product of Array Except Self (LeetCode 238)
- 3Sum (LeetCode 15)
- Kadaneβs Algorithm β Maximum Subarray (LeetCode 53)
- Next Permutation (LeetCode 31)
Hard
- Trapping Rain Water (LeetCode 42)
- First Missing Positive (LeetCode 41)
- Median of Two Sorted Arrays (LeetCode 4)
Also recommended: HackerRank βArraysβ track, Codeforces problems tagged implementation + arrays (start around 800-1200 rating), GeeksforGeeks βArray Data Structureβ practice set.
14. Common Mistakes
- Off-by-one errors: using
<=instead of<in loop bounds, or vice versa. - Not checking capacity before writing, causing buffer overflows in manual implementations.
- Forgetting to free heap memory (memory leaks) or double-freeing (undefined behavior).
- Assuming O(1) insert everywhere β many beginners forget that inserting anywhere but the end is O(n).
- Confusing size and capacity in dynamic arrays, leading to reading garbage/uninitialized memory.
- Shifting in the wrong direction during insert/delete operations, silently corrupting data.
- Ignoring cache effects β assuming a linked list with the βsame Big-Oβ will perform the same as an array in practice; contiguous memory is often 2-10x faster in real benchmarks due to CPU cache behavior.
15. Summary
Key takeaways:
- Arrays trade flexibility for speed: O(1) access, but O(n) structural changes.
- Dynamic arrays achieve amortized O(1) append via geometric (doubling) growth.
- Arrays are the foundation for almost every other data structure covered in this guide (heaps, hash tables, and even trees are often array-backed under the hood).
Complexity recap:
| Access | Search | Insert (end) | Insert (middle) | Delete (end) | Delete (middle) |
|---|---|---|---|---|---|
| O(1) | O(n) / O(log n) sorted | O(1) amortized | O(n) | O(1) | O(n) |
Decision guideline: Reach for an array (or dynamic array/vector) when you need fast random access and your insertions/deletions are mostly at the end. Reach for something else (Linked List, Deque) when you need frequent insert/delete at arbitrary positions.
Next chapter: 02_strings.md (String β arrays of characters plus pattern-matching algorithms) or 03_linked_lists.md, whichever youβd like built next.
Chapter 2: Strings (Pattern Matching β KMP, Z-Function, Rabin-Karp)
Study time: ~7-9 hours | Prerequisite: Arrays | Difficulty: Beginner (basics) to Advanced (pattern-matching algorithms)
1. Introduction
Definition: A string is an array of characters β everything from Chapter 1 (Arrays) applies directly, with one addition: strings come with a rich set of substring/pattern-matching problems (βdoes text T contain pattern P? where? how many times?β) that are common and important enough to deserve dedicated, highly-optimized algorithms.
Purpose: To efficiently search for, compare, and manipulate sequences of characters β and specifically, to find occurrences of a smaller pattern inside a larger text in far better than the naive O(nΒ·m) time (text length n, pattern length m) that a brute-force check-every-position approach requires.
Real-world analogy: Searching for a phrase in a book by brute force means, at every single page position, checking character-by-character whether the phrase starts there β extremely wasteful, since most positions fail almost immediately and tell you nothing useful about where to look next. A smart pattern-matching algorithm is like a reader who, upon a partial match failing, immediately knows β from what theyβd already read β exactly how far they can safely skip ahead, never re-reading text theyβve effectively already ruled out.
Motivation: String searching is everywhere β text editorsβ βfindβ feature, DNA sequence matching in bioinformatics, detecting plagiarism, network intrusion detection (matching known attack signatures in traffic), and search engines. The naive approach becomes a real bottleneck at scale (large texts, many repeated searches), motivating algorithms that exploit the structure of the pattern itself to skip redundant comparisons.
History: The Knuth-Morris-Pratt (KMP) algorithm was published in 1977 (Knuth, Morris, and Pratt); Rabin-Karp followed in 1987 (Rabin and Karp), using a completely different hashing-based strategy; the Z-function is a more modern, versatile building block that elegantly solves pattern matching and several related problems using one unified array.
2. Why Do We Need It?
Problem it solves: Finding all occurrences of a pattern P (length m) within a text T (length n) faster than the naive O(nΒ·m) brute-force approach β ideally in O(n + m).
Why the naive approach is insufficient: Brute force slides the pattern across every possible starting position in the text and, at each position, compares character by character until a mismatch or a full match. Its worst case (e.g., text = βaaaaaaaaaaβ¦aβ, pattern = βaaaaβ¦abβ) re-does almost the same wasted comparisons at every single shifted position β O(nΒ·m) total, which is far too slow for large texts or patterns (e.g., searching a short pattern in a multi-gigabyte genome file).
Trade-offs:
- You gain O(n + m) matching (KMP, Z-function) or expected O(n + m) with tiny worst-case risk (Rabin-Karp, due to hash collisions) β both dramatically better than brute force.
- You pay for it with O(m) preprocessing time/space to build an auxiliary structure (KMPβs βfailure function,β the Z-array, or Rabin-Karpβs rolling hash) before the actual search begins β a worthwhile one-time cost that pays for itself immediately when scanning any text of meaningful length.
3. Internal Working
(a) KMP Algorithm β the βfailure functionβ / βlongest proper prefix-suffixβ (LPS) array
Core idea: Precompute, for every prefix of the pattern, the length of the longest proper prefix of that prefix which is also a suffix of it. This tells you, upon a mismatch during matching, exactly how far you can shift the pattern without re-checking characters youβve already confirmed match β because the LPS array already tells you the longest reusable overlap.
LPS array for pattern βABABACβ:
Pattern: A B A B A C
Index: 0 1 2 3 4 5
LPS: 0 0 1 2 3 0
Reading LPS[4]=3 means: the prefix βABABAβ (length 5, index 0-4) has its longest proper prefix-thatβs-also-a-suffix being βABAβ (length 3).
Matching walkthrough β text = βABABABACβ, pattern = βABABACβ:
Compare text[0..5]="ABABAB" vs pattern="ABABAC":
A=A, B=B, A=A, B=B, A=A, Bβ C β MISMATCH at pattern index 5.
Naive approach: shift by 1, restart comparison from scratch β wasteful.
KMP: consult LPS[5-1]=LPS[4]=3 β we know the last 3 matched characters ("ABA")
are also a valid prefix of the pattern β so instead of restarting from
pattern index 0, resume comparing from pattern index 3 (LPS value),
without re-checking those 3 characters at all.
Continue: text[5]='B' vs pattern[3]='B' β match. text[6]='A' vs pattern[4]='A' β match.
text[7]='C' vs pattern[5]='C' β match. FULL MATCH found at text index 2.
Why this is O(n+m): building the LPS array is O(m) (each character processed via similar overlap logic, done once), and the main scan through the text is O(n) β crucially, the text pointer only ever moves forward, never backtracks, while the pattern pointer uses the LPS array to βsmart jumpβ instead of restarting β giving strictly linear total work.
(b) Z-Function β one array, many uses
Core idea: For a string S, the Z-arrayβs entry Z[i] = the length of the longest substring starting at i that is also a prefix of S. To find pattern P in text T, form the combined string P + "$" + T (using a separator character $ guaranteed not to appear in either), compute its Z-array, and any position where Z[i] == length(P) marks a full match of P within T.
Example: S = βaabxaabxcaabxaabβ, finding pattern βaabβ via combined string "aab$" + Sβ¦ (conceptually β the Z-array is computed once over the combined string, and every index where the Z-value equals the patternβs length is a match location).
Why this generalizes KMP: The Z-function directly encodes βhow much of the prefix repeats starting here,β which is a more general and often more intuitive tool than KMPβs LPS array β the same Z-array can also solve string periodicity questions, finding all borders of a string, and computing the LPS array itself in a unified way, whereas KMPβs LPS array is narrowly specialized to just the matching task.
(c) Rabin-Karp β hashing-based matching
Core idea: Instead of comparing characters directly, compute a rolling hash of every length-m substring of the text and compare it to the patternβs hash β if the hashes match, do a (cheap, rare) direct character verification to rule out a hash collision; otherwise, skip immediately.
Rolling hash β the key trick: naively recomputing a hash for every new window would be O(m) per window (O(nΒ·m) total, no better than brute force). Instead, a rolling hash lets you compute the next windowβs hash from the current one in O(1):
hash(T[i+1..i+m]) = (hash(T[i..i+m-1]) - T[i]*base^(m-1)) * base + T[i+m]
"remove the old leading character" "shift and add the new trailing character"
This O(1) update per position is what gives Rabin-Karp its O(n+m) expected time β computing n rolling-hash updates (O(n)) plus the initial pattern hash (O(m)).
Text: "ABCDAB", Pattern: "CDA" (m=3). Rolling hash with base=10 (illustrative, not a real hash base):
hash("ABC") computed directly = some value H1.
hash("BCD") = (H1 - 'A'*10^2) * 10 + 'D' β O(1) update, not recomputed from scratch.
hash("CDA") = (H_BCD - 'B'*10^2) * 10 + 'A' β compare this to hash("CDA") pattern hash β MATCH β verify directly β confirmed.
4. Operations
KMP β Build LPS array:
- For each position i in the pattern, extend the previous longest prefix-suffix match, falling back via the LPS array itself when a character doesnβt extend the match (a clever βlook up your own previous workβ recursive-feeling but actually linear process).
- O(m).
KMP β Search:
- Walk the text with one pointer; walk the pattern with another. On a match, advance both. On a mismatch, consult the LPS array to know how far to βsmart jumpβ the pattern pointer (never the text pointer, which always moves forward).
- O(n).
Z-Function β Build:
- Maintain a window
[L, R]representing the rightmost Z-box found so far (a maximal match against the prefix); use previously computed Z-values to skip redundant comparisons when a new position falls inside that window, extending only when needed. - O(n) for a string of length n (amortized β the windowβs right edge only ever moves forward).
Rabin-Karp β Build initial hash + Search:
- Compute the patternβs hash and the textβs first windowβs hash directly, O(m).
- Slide the window across the text, updating the hash in O(1) each step; on a hash match, verify with a direct character comparison (O(m) worst case per verification, but rare in practice with a good hash function).
- O(n) expected total; O(nΒ·m) worst case under adversarial input or a poor hash function causing many collisions.
Common string operations (built on Arrays, Chapter 1): concatenation, substring extraction, comparison β all inherit arrayβs complexity characteristics (O(n) for most whole-string operations, O(1) for single-character access) unless a languageβs specific string implementation adds its own optimizations (e.g., some languages use rope structures for very large, frequently-edited strings, trading O(1) access for better edit performance).
5. Time & Space Complexity
| Algorithm | Preprocessing | Search | Space | Notes |
|---|---|---|---|---|
| Brute Force | O(1) | O(nΒ·m) worst case | O(1) | Simple but slow on adversarial input |
| KMP | O(m) | O(n) | O(m) for LPS array | Worst-case guaranteed O(n+m) total |
| Z-Function | O(n+m) (on combined string) | (built into preprocessing) | O(n+m) for Z-array | Also solves periodicity, borders, and more |
| Rabin-Karp | O(m) | O(n) expected, O(nΒ·m) worst case | O(1) extra (just the rolling hash) | Worst case only under hash collisions; easily randomized away |
Why these hold:
- KMPβs O(n) search comes from the invariant that the text pointer never moves backward β every character in the text is examined a bounded number of times overall (the amortized argument is subtle but the practical guarantee is airtight: total comparisons across the whole search are O(n)).
- The Z-functionβs O(n) build relies on the same βnever redo work already implied by a previous computationβ principle β the window
[L,R]tracking the rightmost known prefix-match only ever extends rightward, bounding total extension work by the stringβs length. - Rabin-Karpβs O(1) rolling hash update is what turns what would otherwise be O(nΒ·m) (recomputing each windowβs hash from scratch) into O(n) β but this guarantee is only βexpected,β since a malicious or unlucky input causing many hash collisions forces the O(m) verification step to run at nearly every position, degrading to O(nΒ·m) in the worst case (mitigated by using a large enough modulus and/or randomized hash base in practice).
6. Advantages
- All three pattern-matching algorithms achieve linear (or expected linear) total time β a dramatic, practically important improvement over brute force for any non-trivial text/pattern size.
- KMPβs guarantee is worst-case airtight β no adversarial input can degrade it, unlike Rabin-Karp.
- Rabin-Karp generalizes elegantly to multiple pattern search (checking a windowβs hash against a set of pattern hashes) and 2D pattern matching, where KMPβs character-by-character logic doesnβt extend as naturally.
- The Z-function is a genuinely multi-purpose tool β beyond matching, it directly solves βfind all periods of a string,β βfind the shortest string whose repetition forms this string,β and related structural string questions.
7. Disadvantages
- KMP and the Z-function require O(m) or O(n) extra space for their auxiliary arrays β usually negligible, but notable compared to Rabin-Karpβs O(1) extra space.
- Rabin-Karpβs worst-case time bound is not guaranteed β it depends on hash quality and can be exploited adversarially if the hash function/modulus is predictable or poorly chosen.
- All three are more intricate to implement correctly than brute force β off-by-one errors in index bookkeeping are common, especially in KMPβs LPS-array construction and the Z-functionβs window-tracking logic.
8. Real-World Applications
- Text Editors / IDEs: βFindβ and βFind and Replaceβ features rely on fast substring search β often KMP or a close relative for guaranteed performance.
- Search Engines: Matching query terms against indexed documents; more advanced multi-pattern variants (Aho-Corasick, built on similar failure-function ideas) handle matching many patterns simultaneously.
- Bioinformatics: DNA/protein sequence matching, where texts can be enormous (entire genomes) and pattern matching needs to be extremely fast and reliable.
- Network Security: Intrusion detection systems match network packet contents against known attack signature patterns in real time.
- Plagiarism Detection: Finding overlapping substrings between documents, often built on rolling-hash techniques closely related to Rabin-Karp.
- Compilers: Lexical analysis (tokenizing source code) uses pattern-matching-adjacent techniques to recognize keywords, identifiers, and symbols.
- Version Control Systems (e.g., git diff): Finding common substrings/matching regions between file versions uses related string-matching and hashing techniques.
9. Implementation (C++17)
#include <iostream>
#include <string>
#include <vector>
// ---------- KMP ALGORITHM ----------
// Build the LPS (Longest Proper Prefix which is also Suffix) array. O(m).
std::vector<int> buildLPS(const std::string& pattern) {
int m = pattern.size();
std::vector<int> lps(m, 0);
int len = 0; // length of the previous longest prefix-suffix match
int i = 1;
while (i < m) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
} else if (len != 0) {
len = lps[len - 1]; // fall back using the LPS array itself β the key trick
} else {
lps[i] = 0;
i++;
}
}
return lps;
}
// KMP search: returns all starting indices where pattern occurs in text. O(n + m).
std::vector<int> kmpSearch(const std::string& text, const std::string& pattern) {
std::vector<int> matches;
int n = text.size(), m = pattern.size();
if (m == 0) return matches;
std::vector<int> lps = buildLPS(pattern);
int i = 0, j = 0; // i = text pointer, j = pattern pointer
while (i < n) {
if (text[i] == pattern[j]) {
i++;
j++;
if (j == m) {
matches.push_back(i - j); // full match found
j = lps[j - 1]; // continue searching for overlapping matches
}
} else if (j != 0) {
j = lps[j - 1]; // smart jump β text pointer i does NOT move
} else {
i++; // no partial match to fall back on
}
}
return matches;
}
// ---------- Z-FUNCTION ----------
// Build the Z-array. Z[i] = length of longest substring starting at i matching a prefix of s. O(n).
std::vector<int> buildZArray(const std::string& s) {
int n = s.size();
std::vector<int> z(n, 0);
int L = 0, R = 0; // the current rightmost "Z-box" window [L, R]
for (int i = 1; i < n; ++i) {
if (i < R) {
z[i] = std::min(R - i, z[i - L]); // reuse previously computed info within the window
}
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {
z[i]++; // extend the match character by character
}
if (i + z[i] > R) {
L = i;
R = i + z[i]; // grow the window rightward
}
}
return z;
}
// Pattern matching via Z-function: pattern + separator + text, then scan for Z[i] == pattern length.
std::vector<int> zSearch(const std::string& text, const std::string& pattern) {
std::vector<int> matches;
std::string combined = pattern + "$" + text; // '$' assumed not to appear in either string
std::vector<int> z = buildZArray(combined);
int m = pattern.size();
for (int i = m + 1; i < static_cast<int>(combined.size()); ++i) {
if (z[i] == m) {
matches.push_back(i - m - 1); // convert combined-string index back to text index
}
}
return matches;
}
// ---------- RABIN-KARP ----------
std::vector<int> rabinKarpSearch(const std::string& text, const std::string& pattern) {
std::vector<int> matches;
int n = text.size(), m = pattern.size();
if (m == 0 || m > n) return matches;
const long long BASE = 256;
const long long MOD = 1000000007LL; // a large prime to reduce collision probability
long long patternHash = 0, textHash = 0, power = 1;
for (int i = 0; i < m - 1; ++i) power = (power * BASE) % MOD; // BASE^(m-1) % MOD
for (int i = 0; i < m; ++i) {
patternHash = (patternHash * BASE + pattern[i]) % MOD;
textHash = (textHash * BASE + text[i]) % MOD;
}
for (int i = 0; i <= n - m; ++i) {
if (patternHash == textHash) {
// Hashes match β verify directly to rule out a (rare) collision.
if (text.substr(i, m) == pattern) {
matches.push_back(i);
}
}
if (i < n - m) {
// Roll the hash forward: remove leading char, shift, add new trailing char. O(1).
textHash = (textHash - text[i] * power % MOD + MOD * BASE) % MOD; // avoid negative mod
textHash = (textHash * BASE + text[i + m]) % MOD;
}
}
return matches;
}
// Example usage
int main() {
std::string text = "ABABABAC";
std::string pattern = "ABABAC";
std::cout << "KMP matches: ";
for (int idx : kmpSearch(text, pattern)) std::cout << idx << " ";
std::cout << "\n"; // 2
std::cout << "Z-function matches: ";
for (int idx : zSearch(text, pattern)) std::cout << idx << " ";
std::cout << "\n"; // 2
std::cout << "Rabin-Karp matches: ";
for (int idx : rabinKarpSearch(text, pattern)) std::cout << idx << " ";
std::cout << "\n"; // 2
return 0;
}
10. Code Walkthrough
buildLPSβs fallback (len = lps[len - 1]): This single line is the entire trick behind KMP β instead of restarting the βhow much overlap do I haveβ computation from scratch on a mismatch, it reuses previously computed LPS values. This is structurally very similar to DSUβs path compression or DPβs memoization: donβt recompute what youβve already figured out.kmpSearchβs two pointers:i(text) andj(pattern). Crucially,inever decreases β every character in the text is looked at a bounded number of times overall, which is exactly why the total search is O(n) and not O(nΒ·m). The βsmart jumpβ (j = lps[j-1]) only ever moves the pattern pointer backward, never the text pointer.buildZArrayβs window[L, R]: When processing indexithat falls inside a previously-found match window, we can bound (viastd::min) how much extension is already known to be valid from a symmetric earlier position (z[i - L]) β extending further only when genuinely necessary. This βdonβt redo already-implied workβ pattern is the same spirit as KMPβs LPS fallback, expressed differently.zSearchβs combined string with$separator: The separator prevents a match from spuriously βbleedingβ across the boundary between pattern and text β without it, a long enough repeated character run near the boundary could produce an incorrect Z-value.- Rabin-Karpβs rolling hash update:
textHash - text[i]*powerremoves the outgoing leading characterβs contribution;* BASE + text[i+m]shifts everything up one digit and adds the new trailing character β exactly the O(1) update formula from section 3. The+ MOD * BASEbefore the final% MODis a defensive trick to avoid negative intermediate values, since C++βs%operator can return negative results for negative operands. - The direct-comparison verification step (
text.substr(i,m) == pattern): This is what makes Rabin-Karp correct despite using hashing β a hash match is only a candidate, never proof, so a cheap direct check confirms or rejects it (rare enough, with a good hash, to keep the amortized cost low).
Common mistakes to watch for here:
- Forgetting the LPS fallback loop entirely (
else if (len != 0)) and just resettinglen = 0on every mismatch β this degrades KMP back to brute-force-like behavior. - Off-by-one in the Z-functionβs window comparison (
i < Rvsi <= R) β a very common source of subtle bugs. - Forgetting to verify a Rabin-Karp hash match directly β treating a hash collision as a guaranteed match introduces false positives.
- Using a small modulus or predictable hash base in Rabin-Karp for security-sensitive matching β makes adversarial hash collisions easy to construct deliberately.
11. Dry Run
KMP: text = βABABABACβ, pattern = βABABACβ. LPS array (computed in section 3): [0,0,1,2,3,0].
| i (text) | j (pattern) | text[i] vs pattern[j] | Action |
|---|---|---|---|
| 0 | 0 | A vs A | match β i=1,j=1 |
| 1 | 1 | B vs B | match β i=2,j=2 |
| 2 | 2 | A vs A | match β i=3,j=3 |
| 3 | 3 | B vs B | match β i=4,j=4 |
| 4 | 4 | A vs A | match β i=5,j=5 |
| 5 | 5 | B vs C | mismatch β j = lps[4] = 3 (i stays at 5!) |
| 5 | 3 | B vs B | match β i=6,j=4 |
| 6 | 4 | A vs A | match β i=7,j=5 |
| 7 | 5 | C vs C | match β i=8,j=6=m β MATCH at i-j = 8-6 = 2 |
Matches at index 2 β confirmed, and notice the text pointer i only ever increased, never backtracked, even through the mismatch at step 6. β
12. Interview Questions
Conceptual:
- Explain how the LPS array lets KMP avoid re-comparing characters after a mismatch.
- Compare KMP, Z-function, and Rabin-Karp β when might you prefer each?
- Why is Rabin-Karpβs worst case O(nΒ·m) despite its expected O(n+m) β what specifically causes the degradation?
- How does the Z-function generalize beyond simple pattern matching?
- Why must the text pointer in KMP never move backward, and why is that the key to its O(n) guarantee?
Coding:
- Implement KMP pattern search.
- Implement the Z-function and use it for pattern matching.
- Implement Rabin-Karp with a rolling hash.
- Longest Palindromic Substring (multiple valid approaches; some use Z-function-adjacent ideas).
- Repeated String Match / find the shortest repeating unit of a string (a classic Z-function or KMP-LPS application).
- Find all anagram substrings of a pattern in a text (sliding window + character frequency, string-specific but array-technique-driven).
Follow-ups / interviewer traps:
- βCan you find ALL occurrences (with overlaps) using KMP, not just the first?β (yes β the
j = lps[j-1]continuation after a full match, shown in the code, handles this) - βHow would you search for multiple patterns simultaneously?β (tests awareness of Aho-Corasick, a trie-based generalization of KMPβs failure-function idea to multiple patterns at once)
- βWhat if the alphabet is huge (e.g., Unicode) β does Rabin-Karpβs hash choice matter more?β (tests understanding of hash collision risk scaling with alphabet size/adversarial input)
13. Practice Problems
Easy
- Implement strStr() (LeetCode 28) β basic substring search, the direct target for KMP/Z-function
- Longest Common Prefix (LeetCode 14)
- Valid Palindrome (LeetCode 125)
Medium
- Repeated Substring Pattern (LeetCode 459) β classic Z-function/KMP-LPS application
- Longest Happy Prefix (LeetCode 1392) β directly the LPS arrayβs definition
- Find All Anagrams in a String (LeetCode 438)
- Group Anagrams (LeetCode 49) β ties back to the Hash Table chapter
Hard
- Shortest Palindrome (LeetCode 214) β KMP-based approach
- Distinct Subsequences (LeetCode 115)
- String Matching in an Array (LeetCode 1408) β practice applying substring search as a building block
Also recommended: Codeforces problems tagged strings at rating 1400-1900, GeeksforGeeks βPattern Searchingβ practice set covering KMP, Z-function, and Rabin-Karp variants side by side.
14. Common Mistakes
- Reverting to brute-force restart logic on a KMP mismatch instead of correctly consulting the LPS arrayβs fallback value.
- Off-by-one errors in Z-function window bounds β a notoriously fiddly piece of code to get exactly right on the first try.
- Trusting a Rabin-Karp hash match without direct verification β a hash collision, while rare, is not impossible, and treating βhashes equalβ as βstrings equalβ introduces silent false positives.
- Using a weak or predictable hash base/modulus in Rabin-Karp, especially in any context where input could be adversarial (e.g., a public-facing search feature).
- Forgetting the separator character in Z-function-based pattern matching, allowing spurious cross-boundary matches.
- Ignoring integer overflow in Rabin-Karpβs hash arithmetic β always use a sufficiently large modulus and take modulo at every intermediate step, not just at the end.
15. Summary
Key takeaways:
- Brute-force string matching is O(nΒ·m); KMP and the Z-function achieve a guaranteed O(n+m) by precomputing structural self-overlap information about the pattern; Rabin-Karp achieves expected O(n+m) via O(1) rolling-hash updates, with a small but real worst-case collision risk.
- KMPβs LPS array and the Z-function solve the same underlying problem from two different but related angles β the Z-function is more general-purpose (periodicity, borders, and more), while KMPβs LPS array is narrowly tuned for matching.
- Rabin-Karpβs hashing approach generalizes especially well to multi-pattern search and 2D matching, where character-by-character failure-function logic doesnβt extend as naturally.
Complexity recap:
| Algorithm | Total Time | Space | Worst case guaranteed? |
|---|---|---|---|
| Brute Force | O(nΒ·m) | O(1) | Yes (but slow) |
| KMP | O(n+m) | O(m) | Yes |
| Z-Function | O(n+m) | O(n+m) | Yes |
| Rabin-Karp | O(n+m) expected | O(1) | No β O(nΒ·m) under hash collisions |
Decision guideline: Use KMP or the Z-function when you need an airtight worst-case guarantee β especially for security-sensitive or adversarial-input contexts. Use Rabin-Karp when you need to search for multiple patterns at once, need 2D pattern matching, or when average-case performance with a well-chosen hash is acceptable. For simple one-off searches in most application code, a languageβs built-in string search (often a well-tuned hybrid) is perfectly fine β reach for these algorithms specifically when performance at scale genuinely matters, or when an interviewer is asking about the underlying mechanics directly.
Next chapter: 03_linked_lists.md
Chapter 2: Linked Lists
Study time: ~5-7 hours | Prerequisite: Arrays, pointers/references | Difficulty: Beginner-Intermediate
1. Introduction
Definition: A linked list is a linear data structure where elements (βnodesβ) are stored in separate memory locations, each holding its data plus a pointer (or reference) to the next node. There is no requirement that nodes sit next to each other in memory.
Purpose: To allow the size of a collection to grow and shrink freely, and to allow O(1) insertion/deletion once youβre positioned at a node β without the βshift everythingβ cost that arrays pay.
Real-world analogy: A treasure hunt. Each clue (node) tells you where to find the next clue. You canβt jump straight to clue #7 β you must follow clue #1 β #2 β β¦ β #7. Compare this to an array, which is like a row of numbered lockers where you can walk straight to locker #7.
Motivation: Arrays require contiguous memory and (for static arrays) a known size upfront. A linked list frees you from both constraints β nodes can live anywhere in memory, and the list grows one node at a time with no bulk reallocation.
History: Introduced in the late 1950s as part of early list-processing languages (IPL, then Lisp), specifically to support of programs that manipulate symbolic, dynamically-sized data.
2. Why Do We Need It?
Problem it solves: Frequent insertion/deletion β especially at the front or middle β without the O(n) shifting cost arrays impose.
Why arrays are insufficient here: Inserting at the front of an array means shifting every existing element one slot right β O(n). A linked list just rewires two pointers β O(1), once youβre already at the right node.
Trade-offs:
- You gain O(1) structural changes (given a node reference) and no need to pre-declare a size.
- You pay for it with O(n) access/search (no random access β you must walk from the head), extra memory per node (for the pointer(s)), and poor cache locality (nodes are scattered, so traversal is slower in practice than array traversal despite both being O(n)).
This is the mirror image of the arrayβs trade-off: arrays are fast to read, slow to restructure; linked lists are slow to read, fast to restructure (once located).
3. Internal Working
Singly Linked List β each node has data + one pointer to the next node:
head
β
βΌ
ββββββ¬βββββ ββββββ¬βββββ ββββββ¬βββββ
β 10 β ββββΌββββΆβ 20 β ββββΌββββΆβ 30 βNULLβ
ββββββ΄βββββ ββββββ΄βββββ ββββββ΄βββββ
Doubly Linked List β each node also has a pointer back to the previous node, enabling backward traversal:
head tail
β β
βΌ βΌ
NULLβββββ¬βββββ¬βββββ ββββββ¬βββββ¬βββββ ββββββ¬βββββ¬βββββ
βprevβ 10 βnextβprevβ 20 βnextβprevβ 30 βnextβββββΆNULL
ββββββ΄βββββ΄ββββΆβ β ββββββ΄βββββ΄βββββ΄βββββ
Circular Linked List β the last node points back to the first instead of NULL:
ββββββ ββββββ ββββββ
β 10 βββββΆβ 20 βββββΆβ 30 β
ββββββ ββββββ ββββββ
β² β
βββββββββββββββββββββ
Insertion at the front (singly linked list), step by step:
Before: head β [10] β [20] β NULL
Insert 5:
Step 1: new node [5] β points to current head [10]
[5] β [10] β [20] β NULL
Step 2: head now points to [5]
head β [5] β [10] β [20] β NULL
Only two pointer operations β no shifting of existing nodes.
4. Operations
Insert
- At head: Create new node, point it to current head, update head. O(1).
- At tail (no tail pointer): Traverse to the end, then link. O(n).
- At tail (tail pointer maintained): O(1).
- At position i: Traverse to node i-1, then relink. O(n) to find + O(1) to relink.
- Edge case: inserting into an empty list β head and tail must both be updated to the new node.
Delete
- At head: Move head to
head->next, free old head. O(1). - At tail (singly linked, no prev pointer): Must traverse to second-to-last node to update its
nextto NULL. O(n). (Doubly linked list: O(1) sinceprevis directly available.) - At position i: Traverse to node i-1, relink around node i, free it. O(n).
- Edge case: deleting the only node in the list β both head and tail must become NULL.
Update
- Traverse to the node, then overwrite its data field. O(n) to locate + O(1) to write.
Search
- Linear traversal from head, comparing each nodeβs data. O(n). No binary search possible β you canβt jump to the middle without already having a pointer there.
Traverse
- Follow
nextpointers until NULL. O(n). Cache-unfriendly compared to array traversal since nodes may be scattered in memory.
Peek
- Head/tail data, O(1) if pointers are maintained.
5. Time & Space Complexity
| Operation | Singly Linked List | Doubly Linked List | Space Complexity |
|---|---|---|---|
| Access by index | O(n) | O(n) | O(1) |
| Search | O(n) | O(n) | O(1) |
| Insert at head | O(1) | O(1) | O(1) extra per node |
| Insert at tail (tail ptr kept) | O(1) | O(1) | O(1) |
| Insert at middle (position known) | O(1) relink, O(n) to find | O(1) relink, O(n) to find | O(1) |
| Delete at head | O(1) | O(1) | O(1) |
| Delete at tail | O(n) | O(1) | O(1) |
| Overall storage | O(n) | O(n), roughly 2x pointer overhead vs singly | β |
Why these hold:
- Access/search must be O(n) because there is no address formula like arrays have β the only way to reach node i is to follow i pointers from the head.
- Insert/delete at head is O(1) because it only touches a fixed number of pointers regardless of list length.
- Deleting the tail in a singly linked list is O(n) because, without a
prevpointer, you must walk from the head to find the node just before the tail. This single fact is the main reason doubly linked lists exist.
6. Advantages
- O(1) insertion/deletion at the head (and tail, if a tail pointer is kept).
- No need to know size in advance; grows one node at a time with no bulk reallocation.
- No wasted pre-allocated capacity (unlike a dynamic arrayβs spare capacity).
- Doubly linked lists allow O(1) removal of a node given only a pointer to it (no need to know its predecessor).
7. Disadvantages
- No random access β O(n) to reach an arbitrary index.
- Extra memory per node for pointer(s) (a doubly linked list roughly doubles the pointer overhead versus singly).
- Poor cache locality β nodes are scattered, so real-world traversal is slower than an arrayβs despite the same Big-O.
- More complex to implement correctly (pointer bugs like memory leaks and dangling pointers are common).
8. Real-World Applications
- Operating Systems: Process scheduling queues (e.g., the Linux kernelβs task list uses a circular doubly linked list).
- Browsers: Forward/back navigation history (doubly linked list β you can go both directions).
- Text Editors: Undo/redo stacks, and some implementations model the document itself as a linked list of lines for O(1) line insertion/deletion.
- Databases: Buffer pool management (LRU eviction, covered later, uses a doubly linked list).
- Music/Media players: βNext/previous trackβ playlist navigation.
- Memory Management: Free lists in memory allocators link together free memory blocks.
- File Systems: Some file systems chain disk blocks belonging to one file via a linked-list-like structure (FAT β File Allocation Table).
Linked lists are chosen wherever items are added/removed frequently and sequential access is fine (you donβt need βgive me item #500,000 instantlyβ).
9. Implementation (C++17)
#include <iostream>
#include <stdexcept>
// A generic doubly linked list β supports O(1) insert/delete at both ends,
// and O(1) deletion given a direct node pointer (a key advantage over singly linked lists).
class DoublyLinkedList {
private:
struct Node {
int data;
Node* prev;
Node* next;
Node(int val) : data(val), prev(nullptr), next(nullptr) {}
};
Node* head;
Node* tail;
size_t sz;
public:
DoublyLinkedList() : head(nullptr), tail(nullptr), sz(0) {}
// Destructor: walk the list and free every node to avoid memory leaks.
~DoublyLinkedList() {
Node* current = head;
while (current != nullptr) {
Node* toDelete = current;
current = current->next;
delete toDelete;
}
}
// Insert at the front. O(1).
void push_front(int value) {
Node* newNode = new Node(value);
if (head == nullptr) { // empty list: new node is both head and tail
head = tail = newNode;
} else {
newNode->next = head;
head->prev = newNode;
head = newNode;
}
sz++;
}
// Insert at the back. O(1) thanks to the maintained tail pointer.
void push_back(int value) {
Node* newNode = new Node(value);
if (tail == nullptr) {
head = tail = newNode;
} else {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
sz++;
}
// Remove from the front. O(1).
void pop_front() {
if (head == nullptr) throw std::underflow_error("pop_front on empty list");
Node* toDelete = head;
head = head->next;
if (head != nullptr) head->prev = nullptr;
else tail = nullptr; // list is now empty
delete toDelete;
sz--;
}
// Remove from the back. O(1) β this is the operation a SINGLY linked list
// cannot do in O(1), because it has no `prev` pointer to reattach the new tail.
void pop_back() {
if (tail == nullptr) throw std::underflow_error("pop_back on empty list");
Node* toDelete = tail;
tail = tail->prev;
if (tail != nullptr) tail->next = nullptr;
else head = nullptr;
delete toDelete;
sz--;
}
// Search by value. O(n).
bool contains(int value) const {
Node* current = head;
while (current != nullptr) {
if (current->data == value) return true;
current = current->next;
}
return false;
}
// Reverse the entire list in-place. O(n) time, O(1) extra space.
// Classic interview question: swap prev/next for every node, then swap head/tail.
void reverse() {
Node* current = head;
Node* temp = nullptr;
while (current != nullptr) {
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev; // move to what was originally the next node
}
temp = head;
head = tail;
tail = temp;
}
size_t size() const { return sz; }
bool empty() const { return sz == 0; }
void print() const {
std::cout << "[ ";
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << "] (size=" << sz << ")\n";
}
};
// Example usage
int main() {
DoublyLinkedList list;
list.push_back(10);
list.push_back(20);
list.push_back(30);
list.print(); // [ 10 20 30 ] (size=3)
list.push_front(5);
list.print(); // [ 5 10 20 30 ] (size=4)
list.pop_back();
list.print(); // [ 5 10 20 ] (size=3)
list.reverse();
list.print(); // [ 20 10 5 ] (size=3)
std::cout << "Contains 10? " << (list.contains(10) ? "yes" : "no") << "\n";
return 0;
}
10. Code Walkthrough
Nodestruct: Nested inside the class since itβs an implementation detail users ofDoublyLinkedListnever touch directly. Holdsdata,prev, andnextβ the three fields that define a doubly linked node.head/tailpointers: Maintaining both is what turns βinsert/delete at tailβ from O(n) into O(1) β the single biggest reason to choose doubly over singly linked.push_front/push_back: Both handle the empty-list case specially (head == nullptr), because with zero nodes thereβs no existing head/tail to link against β the new node becomes both.pop_front/pop_back: Notice the symmetry βpop_frontmovesheadforward and nulls the new headβsprev;pop_backmovestailbackward and nulls the new tailβsnext. Getting this null-ing step wrong is what causes dangling pointers.reverse(): The trick is swappingprevandnextfor every node, then finally swappingheadandtail. Beginners often forget the final head/tail swap, leaving the list logically reversed internally but withheadstill pointing at the old first node.- Destructor: Must walk and
deleteevery node individually β unlike an arrayβs singledelete[], freeing a linked list requires touching every node because each is a separate heap allocation.
Common mistakes to watch for here:
- Forgetting to update
prev/nexton both neighboring nodes when inserting/deleting in the middle. - Losing the reference to the next node before advancing (
current = current->nexttoo early, causing a memory leak when you meant to deletecurrentfirst). - Not handling the empty-list or single-node cases separately (these are the most common source of segfaults).
11. Dry Run
Input: push_back(10), push_back(20), push_back(30), push_front(5), pop_back(), reverse()
| Step | Operation | State | head | tail |
|---|---|---|---|---|
| 0 | init | [] | NULL | NULL |
| 1 | push_back(10) | [10] | 10 | 10 |
| 2 | push_back(20) | [10,20] | 10 | 20 |
| 3 | push_back(30) | [10,20,30] | 10 | 30 |
| 4 | push_front(5) | [5,10,20,30] | 5 | 30 |
| 5 | pop_back() | [5,10,20] | 5 | 20 |
| 6 | reverse() | [20,10,5] | 20 | 5 |
Reverse, step by step on [5,10,20]:
- Node 5: prev=NULL, next=10 β after swap: prev=10, next=NULL
- Node 10: prev=5, next=20 β after swap: prev=20, next=5
- Node 20: prev=10, next=NULL β after swap: prev=NULL, next=10
- Final swap: head (was 5) and tail (was 20) swap β head=20, tail=5
- Traversal from new head: 20 β 10 β 5 β
12. Interview Questions
Conceptual:
- Why is deleting the tail O(1) in a doubly linked list but O(n) in a singly linked list?
- Compare memory overhead: array vs singly linked list vs doubly linked list.
- When would you choose a linked list over a dynamic array despite both being O(n) worst case for search?
- Explain why linked lists have poor cache performance despite O(1) insert/delete.
- Whatβs a circular linked list used for, and how do you detect the βendβ without a NULL terminator?
Coding:
- Reverse a linked list (iterative and recursive).
- Detect a cycle in a linked list (Floydβs Tortoise and Hare).
- Find the middle node in one pass.
- Merge two sorted linked lists.
- Remove the nth node from the end (one-pass, two-pointer technique).
- Detect and remove a cycle, finding its starting node.
- Check if a linked list is a palindrome.
Follow-ups / interviewer traps:
- βCan you reverse it recursively? Whatβs the space complexity then?β (recursion uses O(n) call stack, unlike O(1) iterative)
- βCan you find the middle without knowing the length first?β (expects slow/fast pointer technique)
- βWhat if the list is circular β does your cycle detection still terminate?β (tests understanding of Floydβs algorithm)
13. Practice Problems
Easy
- Reverse Linked List (LeetCode 206)
- Merge Two Sorted Lists (LeetCode 21)
- Linked List Cycle (LeetCode 141)
- Middle of the Linked List (LeetCode 876)
Medium
- Add Two Numbers (LeetCode 2)
- Remove Nth Node From End of List (LeetCode 19)
- Reorder List (LeetCode 143)
- Copy List with Random Pointer (LeetCode 138)
- Rotate List (LeetCode 61)
Hard
- Merge k Sorted Lists (LeetCode 23)
- Reverse Nodes in k-Group (LeetCode 25)
- LRU Cache (LeetCode 146) β previewed here, full chapter later
Also recommended: GeeksforGeeks βLinked Listβ practice set, HackerRank βLinked Listsβ track, Codeforces problems tagged data structures involving list-like manipulation.
14. Common Mistakes
- Losing the head pointer by reassigning it before saving a reference to the rest of the list.
- Not updating both
prevandnexton neighboring nodes during middle insert/delete in a doubly linked list. - Memory leaks β deleting a node without first saving a pointer to its
next, then losing access to the rest of the list. - Dangling pointers β using a node after itβs been freed.
- Off-by-one in traversal when searching for the node before the target (needed for singly-linked deletion).
- Forgetting the empty-list and single-node edge cases, which behave differently from the general case (no βpreviousβ node exists, head and tail coincide).
- Assuming O(n) traversal performs like an arrayβs O(n) traversal β pointer-chasing across scattered memory is slower in practice due to cache misses.
15. Summary
Key takeaways:
- Linked lists trade random access for O(1) structural changes β exactly the opposite trade-off of arrays.
- Doubly linked lists exist specifically to make tail deletion and arbitrary-node deletion O(1), at the cost of extra memory per node.
- Many classic interview problems (cycle detection, reversal, merging) are really pointer-manipulation exercises β draw the pointers on paper before coding.
Complexity recap:
| Access | Search | Insert (head) | Insert (tail) | Delete (head) | Delete (tail) | |
|---|---|---|---|---|---|---|
| Singly Linked | O(n) | O(n) | O(1) | O(1)* | O(1) | O(n) |
| Doubly Linked | O(n) | O(n) | O(1) | O(1) | O(1) | O(1) |
*O(1) only if a tail pointer is maintained.
Decision guideline: Choose a linked list (over an array) when you need frequent insertion/deletion at both ends or in the middle (given a node reference), and you donβt need random access by index. Choose doubly linked specifically when you need O(1) deletion of an arbitrary node or backward traversal (e.g., LRU caches, browser history, undo/redo).
Next chapter: 03_stack_and_queue.md
Chapter 3: Stack & Queue
Study time: ~4-6 hours | Prerequisite: Arrays, Linked Lists | Difficulty: Beginner-Intermediate
1. Introduction
Definition: A Stack is a linear data structure that follows LIFO (Last In, First Out) β the most recently added element is the first one removed. A Queue follows FIFO (First In, First Out) β the earliest added element is the first one removed. Both are restricted interfaces layered on top of an array or linked list: they donβt allow arbitrary access, only access at defined ends.
Purpose: To enforce a strict order of processing β βundo the last thingβ (stack) or βserve whoever arrived firstβ (queue) β without exposing the full flexibility (and risk of misuse) of a raw array or list.
Real-world analogy:
- Stack = a stack of plates. You can only take the top plate off, and you can only add a new plate on top.
- Queue = a checkout line. The first person to join is the first person served; new people join at the back.
Motivation: Many real problems have a natural βreverse orderβ (stack) or βarrival orderβ (queue) requirement β function calls returning in reverse order of being called, or print jobs processing in the order submitted. Building a dedicated structure with only push/pop or enqueue/dequeue prevents bugs from accidentally reading/writing the middle of the collection.
2. Why Do We Need It?
Problem it solves: Enforcing a specific access discipline (LIFO or FIFO) so algorithms that depend on that order (backtracking, BFS, task scheduling) behave correctly and are easy to reason about.
Why raw arrays/lists are insufficient: You could use a plain array for both, but nothing stops you from accidentally reading/writing the middle, which breaks the LIFO/FIFO invariant the algorithm depends on. A dedicated Stack/Queue interface makes misuse a compile-time or immediate runtime error.
Trade-offs:
- You gain guaranteed O(1) operations at the defined access point(s) and a self-documenting interface (
push/popsignals LIFO intent to any reader of the code). - You lose general-purpose access β you cannot peek at the 3rd element of a stack without popping the first two.
3. Internal Working
Stack (array-backed) β grows and shrinks only at one end, the βtopβ:
push(30): pop():
ββββββ ββββββ
β 30 β β top β 20 β β top (30 removed)
ββββββ€ ββββββ€
β 20 β β 10 β
ββββββ€ ββββββ
β 10 β
ββββββ
Queue (circular-array-backed) β enqueue at rear, dequeue at front. A circular buffer avoids wasting space after repeated dequeues:
Initial: front=0, rear=-1, empty
enqueue(10): [10, _, _, _] front=0 rear=0
enqueue(20): [10,20, _, _] front=0 rear=1
enqueue(30): [10,20,30, _] front=0 rear=2
dequeue(): [ _,20,30, _] front=1 rear=2 (10 logically removed)
enqueue(40): [ _,20,30,40] front=1 rear=3
enqueue(50): rear wraps around to index 0 (circular!) β [50,20,30,40] front=1 rear=0
Without the circular wraparound, a plain array-backed queue would βleakβ the freed front slots and eventually run out of room even with elements removed.
Stack via recursion / call stack (why itβs called a βstackβ):
main() calls f(3)
f(3) calls f(2)
f(2) calls f(1)
f(1) returns
f(2) resumes and returns
f(3) resumes and returns
main() resumes
Call stack grows: [main] β [main,f(3)] β [main,f(3),f(2)] β [main,f(3),f(2),f(1)]
Then unwinds in exact reverse order β LIFO.
4. Operations
Stack
- push(x): Place x at the top. O(1).
- pop(): Remove and return the top element. O(1). Edge case: popping an empty stack β underflow error.
- peek()/top(): View the top element without removing. O(1).
- isEmpty(): O(1).
- No search/traverse in the βpureβ interface β if you need to search, youβre arguably using the wrong structure.
Queue
- enqueue(x): Place x at the rear. O(1).
- dequeue(): Remove and return the front element. O(1). Edge case: dequeuing an empty queue β underflow error.
- front()/peek(): View the front element without removing. O(1).
- isEmpty(): O(1).
- Circular array edge case: rear must wrap using modulo (
rear = (rear + 1) % capacity), and you must distinguish βemptyβ from βfullβ (both can look likefront == rearwithout a size counter).
Deque (double-ended queue) β generalizes both:
push_front,push_back,pop_front,pop_backβ all O(1). A deque can simulate both a stack and a queue.
5. Time & Space Complexity
| Operation | Stack | Queue | Space Complexity |
|---|---|---|---|
| push / enqueue | O(1) | O(1) | O(1) per element |
| pop / dequeue | O(1) | O(1) | O(1) |
| peek / front | O(1) | O(1) | O(1) |
| isEmpty | O(1) | O(1) | O(1) |
| Search (if needed) | O(n) | O(n) | O(1) |
| Overall storage | O(n) | O(n) | O(n) |
Why these hold: Every core operation touches only a fixed, known location (the top, or the front/rear) β never requiring a scan of the rest of the structure. This is true whether the backing store is an array (with a top/front/rear index) or a linked list (with a head/tail pointer) β the O(1) guarantee comes from restricting access to defined ends, not from any particular backing implementation.
6. Advantages
- Both guarantee O(1) for their core operations, with essentially no overhead beyond the backing structure.
- The restricted interface makes code that uses them self-documenting and harder to misuse (a stack signals βI only care about the most recent itemβ; a queue signals βI process things in arrival orderβ).
- Directly mirror common real-world/algorithmic patterns (undo history, BFS traversal, task scheduling), making translation from problem statement to code very direct.
7. Disadvantages
- No random access β canβt inspect the middle without destructively popping through it.
- Array-backed stacks/queues need resizing logic (same cost profile as dynamic arrays) unless capacity is fixed and known upfront.
- A naive (non-circular) array-backed queue wastes space at the front after repeated dequeues unless a circular buffer or periodic compaction is used.
8. Real-World Applications
Stack
- Compilers: Expression evaluation, syntax parsing (matching brackets/parentheses), the function call stack itself.
- Browsers: The βbackβ button history is a stack of visited pages.
- Text Editors: Undo functionality β each action pushed onto a stack, popped on undo.
- Operating Systems: Each thread has its own call stack for function invocation and local variables.
Queue
- Operating Systems: CPU task scheduling (round-robin), print job spooling.
- Networking: Packet buffering at routers β packets processed in arrival order.
- Social Media: Notification queues, message queues (Kafka, RabbitMQ) that process events in order.
- Customer Service Systems: Ticket queues β first-come-first-served support.
- BFS traversal in Graph and Tree algorithms (covered in the Graphs chapter) is built entirely on a queue.
9. Implementation (C++17)
#include <iostream>
#include <stdexcept>
// ---------- STACK: array-backed, LIFO ----------
class Stack {
private:
int* data;
size_t cap;
size_t topIdx; // number of elements currently stored (also "next free slot")
void resize(size_t newCap) {
int* newData = new int[newCap];
for (size_t i = 0; i < topIdx; ++i) newData[i] = data[i];
delete[] data;
data = newData;
cap = newCap;
}
public:
Stack() : data(new int[1]), cap(1), topIdx(0) {}
~Stack() { delete[] data; }
// Push. Amortized O(1) β same doubling strategy as dynamic array.
void push(int value) {
if (topIdx == cap) resize(cap * 2);
data[topIdx++] = value;
}
// Pop. O(1). Throws on empty stack β never silently return garbage.
int pop() {
if (isEmpty()) throw std::underflow_error("pop on empty stack");
return data[--topIdx];
}
// Peek at top without removing. O(1).
int peek() const {
if (isEmpty()) throw std::underflow_error("peek on empty stack");
return data[topIdx - 1];
}
bool isEmpty() const { return topIdx == 0; }
size_t size() const { return topIdx; }
};
// ---------- QUEUE: circular-array-backed, FIFO ----------
class Queue {
private:
int* data;
size_t cap;
size_t frontIdx;
size_t count; // number of elements currently stored
void resize(size_t newCap) {
int* newData = new int[newCap];
// Copy elements out in logical order (front to rear), re-linearizing the circular buffer.
for (size_t i = 0; i < count; ++i) {
newData[i] = data[(frontIdx + i) % cap];
}
delete[] data;
data = newData;
cap = newCap;
frontIdx = 0;
}
public:
Queue() : data(new int[1]), cap(1), frontIdx(0), count(0) {}
~Queue() { delete[] data; }
// Enqueue at the rear. Amortized O(1).
void enqueue(int value) {
if (count == cap) resize(cap * 2);
size_t rearIdx = (frontIdx + count) % cap; // circular wraparound
data[rearIdx] = value;
count++;
}
// Dequeue from the front. O(1).
int dequeue() {
if (isEmpty()) throw std::underflow_error("dequeue on empty queue");
int value = data[frontIdx];
frontIdx = (frontIdx + 1) % cap; // circular wraparound
count--;
return value;
}
// Peek at front without removing. O(1).
int front() const {
if (isEmpty()) throw std::underflow_error("front on empty queue");
return data[frontIdx];
}
bool isEmpty() const { return count == 0; }
size_t size() const { return count; }
};
// Example usage
int main() {
Stack s;
s.push(10); s.push(20); s.push(30);
std::cout << "Stack top: " << s.peek() << "\n"; // 30
std::cout << "Popped: " << s.pop() << "\n"; // 30
std::cout << "Popped: " << s.pop() << "\n"; // 20
std::cout << "Stack size: " << s.size() << "\n"; // 1
Queue q;
q.enqueue(10); q.enqueue(20); q.enqueue(30);
std::cout << "Queue front: " << q.front() << "\n"; // 10
std::cout << "Dequeued: " << q.dequeue() << "\n"; // 10
std::cout << "Dequeued: " << q.dequeue() << "\n"; // 20
q.enqueue(40);
std::cout << "Queue size: " << q.size() << "\n"; // 2
return 0;
}
10. Code Walkthrough
- Stackβs
topIdx: Doubles as both βhow many elements are storedβ and βthe next free slot index.βpushwrites todata[topIdx]then increments;popdecrements first, then reads β this ordering matters and is a common off-by-one trap. - Stack
resize: Identical doubling strategy to the Dynamic Array chapter β stacks and dynamic arrays share the same amortized-O(1)-growth logic, since a stack is essentially a dynamic array restricted to one access point. - Queueβs circular indexing (
(frontIdx + count) % cap): This is the crux of the whole implementation. Without the modulo,rearIdxwould keep growing forever even as elements are dequeued from the front, eventually running past the allocated array despite there being free (dequeued) slots at the beginning. - Queueβs
resize: Note it re-linearizes the circular buffer β it doesnβt just copydata[0..cap)verbatim (that would copy stale/wrapped-around data in the wrong order). It walkscountelements starting from the logical front, using modulo again, and resetsfrontIdxto 0 in the new block. - Why
countinstead of comparingfrontIdx == rearIdx: A common queue bug is trying to detect βfullβ vs βemptyβ using only front/rear indices β both states can producefront == rear. Trackingcountexplicitly sidesteps this ambiguity entirely.
Common mistakes to watch for here:
- Forgetting the modulo wraparound in a circular queue, causing an index-out-of-bounds write.
- Using
front == rearalone to detect empty/full (ambiguous) instead of a dedicated counter. - Off-by-one between incrementing/decrementing
topIdxbefore vs. after reading/writing.
11. Dry Run
Stack β Input: push(10), push(20), push(30), pop(), peek()
| Step | Operation | State (topβbottom) | Returns |
|---|---|---|---|
| 1 | push(10) | [10] | β |
| 2 | push(20) | [20,10] | β |
| 3 | push(30) | [30,20,10] | β |
| 4 | pop() | [20,10] | 30 |
| 5 | peek() | [20,10] | 20 |
Queue (capacity 4) β Input: enqueue(10,20,30), dequeue(), enqueue(40), enqueue(50)
| Step | Operation | frontIdx | count | Array (logical) | Notes |
|---|---|---|---|---|---|
| 1 | enqueue(10) | 0 | 1 | [10] | |
| 2 | enqueue(20) | 0 | 2 | [10,20] | |
| 3 | enqueue(30) | 0 | 3 | [10,20,30] | |
| 4 | dequeue() β 10 | 1 | 2 | [20,30] | front slot logically freed |
| 5 | enqueue(40) | 1 | 3 | [20,30,40] | rear = (1+2)%4 = 3 |
| 6 | enqueue(50) | 1 | 4 | [20,30,40,50] | rear = (1+3)%4 = 0 β wraps to index 0! |
At step 6, 50 physically lands at array index 0 (wrapping around), even though logically itβs the newest, rear-most element β this is exactly why circular indexing works without wasting the freed front slots.
12. Interview Questions
Conceptual:
- Why does a naive array-backed queue βwasteβ space after repeated dequeues, and how does a circular buffer fix it?
- How would you implement a Queue using two Stacks (and vice versa)?
- Whatβs the relationship between a Stack and recursion / the call stack?
- When would you use a Deque instead of a plain Stack or Queue?
- Why canβt
front == rearalone reliably distinguish an empty circular queue from a full one?
Coding:
- Implement a Queue using two Stacks.
- Implement a Stack using a single Queue.
- Valid Parentheses β check balanced brackets using a stack.
- Design a Min Stack (push/pop/getMin all O(1)).
- Evaluate a Reverse Polish Notation (postfix) expression.
- Implement a sliding window maximum using a Deque (monotonic deque technique).
- Next Greater Element β using a monotonic stack.
Follow-ups / interviewer traps:
- βCan you get O(1) amortized for both push and pop in the two-stack Queue?β (yes β lazy transfer between stacks)
- βWhat if you need getMin() in O(1) on your Min Stack β can you do it without extra space per element?β (expects storing running-min alongside each value, or a secondary stack)
- After Sliding Window Maximum: βWhy is a monotonic deque O(n) total instead of O(nk)?β (tests amortized analysis understanding)
13. Practice Problems
Easy
- Valid Parentheses (LeetCode 20)
- Implement Stack using Queues (LeetCode 225)
- Implement Queue using Stacks (LeetCode 232)
- Baseball Game (LeetCode 682)
Medium
- Min Stack (LeetCode 155)
- Evaluate Reverse Polish Notation (LeetCode 150)
- Daily Temperatures β monotonic stack (LeetCode 739)
- Next Greater Element II (LeetCode 503)
- Design Circular Queue (LeetCode 622)
Hard
- Sliding Window Maximum (LeetCode 239)
- Largest Rectangle in Histogram (LeetCode 84)
- Trapping Rain Water using Stack (LeetCode 42, stack-based approach)
Also recommended: GeeksforGeeks βStackβ and βQueueβ practice sets, HackerRank βStacks and Queuesβ track, Codeforces problems tagged data structures + implementation involving monotonic stacks/deques.
14. Common Mistakes
- Popping/dequeuing without checking for empty first β causes undefined behavior or crashes.
- Forgetting the circular wraparound modulo in an array-backed queue, leading to out-of-bounds access or βfalse fullβ errors.
- Confusing Stack and Queue semantics when translating a problem into code (e.g., using a Stack for BFS, which should use a Queue β this silently produces DFS-order results instead).
- Not resizing a fixed-capacity array-backed stack/queue and overflowing it.
- Assuming a
std::stack/std::queuesupports iteration or random access β by design (in the STL, these are βcontainer adaptersβ), they intentionally donβt expose iterators, mirroring the βrestricted accessβ philosophy of section 2. - In Min Stack problems: storing only the global minimum instead of a minimum-at-each-push-time, which breaks when the actual minimum is popped.
15. Summary
Key takeaways:
- Stack = LIFO, Queue = FIFO β the only difference between them is which end you remove from; everything else (O(1) core ops, restricted interface, array or linked-list backing) is shared.
- A circular buffer is what makes an array-backed queue efficient β without it, you either waste space or need O(n) compaction.
- Both structures are less βdata structures to master deeplyβ and more βdisciplines to recognizeβ β the real skill is spotting when a problem has LIFO or FIFO structure (undo β stack; BFS/scheduling β queue).
Complexity recap:
| push/enqueue | pop/dequeue | peek | Space | |
|---|---|---|---|---|
| Stack | O(1) amortized | O(1) | O(1) | O(n) |
| Queue (circular array) | O(1) amortized | O(1) | O(1) | O(n) |
Decision guideline: Use a Stack when the most recently seen item needs to be processed first (undo, backtracking, expression parsing, DFS via explicit stack). Use a Queue when items must be processed in arrival order (task scheduling, BFS, buffering). Use a Deque when you need both ends flexible (sliding window problems).
Next chapter: 04_heaps.md β Max-Heap & Min-Heap
Chapter 4: Heaps (Max-Heap & Min-Heap)
Study time: ~6-8 hours | Prerequisite: Arrays, Binary Trees (conceptually), Recursion | Difficulty: Intermediate
1. Introduction
Definition: A heap is a specialized tree-based structure that satisfies the heap property:
- Max-Heap: every parent nodeβs value β₯ its childrenβs values (the maximum is always at the root).
- Min-Heap: every parent nodeβs value β€ its childrenβs values (the minimum is always at the root).
A heap is also a complete binary tree β every level is fully filled except possibly the last, which fills left to right with no gaps. This completeness is why a heap can be stored efficiently in a plain array with no pointers at all.
Purpose: To provide O(1) access to the current minimum (or maximum) element, with O(log n) insertion and removal β dramatically better than the O(n) it would take to find the min/max in an unsorted array, or the O(n) it costs to insert into a fully sorted array.
Real-world analogy: A hospital emergency room triage queue. Itβs not FIFO (first come, first served) β the most critical patient is always seen next, regardless of arrival order. New patients can arrive and jump ahead of less critical ones already waiting, but only the very top of the priority list is ever pulled.
Motivation: Many problems need repeated access to βthe current best/worst item so farβ while the set of items keeps changing (dynamic scheduling, streaming top-k, graph algorithms). Sorting the whole set every time is wasteful; a heap keeps just enough order to answer βwhatβs the min/max right now?β instantly while staying cheap to update.
History: Invented by J.W.J. Williams in 1964 as part of introducing Heapsort β the heap was originally a sorting tool before becoming a standalone data structure (the Priority Queue).
2. Why Do We Need It?
Problem it solves: βGive me the current smallest/largest element, quickly, over and over, even as elements are added and removedβ β this is the priority queue problem.
Why previous structures are insufficient:
- Unsorted array: finding min/max is O(n) every time.
- Sorted array: finding min/max is O(1), but inserting a new element to keep it sorted is O(n) (must shift to the correct position).
- BST: can find min/max in O(log n) (leftmost/rightmost node) and insert in O(log n) β better, but a heap does the same job with a simpler, more memory-efficient array-backed structure, because it doesnβt need to maintain full sorted order β only the much weaker βparent beats childrenβ property.
Trade-offs:
- You gain O(1) peek at the min/max and O(log n) insert/remove, using a compact array with zero pointer overhead.
- You lose the ability to efficiently find or access any other element β a heap only βknowsβ where its min/max is; finding the 2nd-smallest, for instance, is not O(1) or even straightforward.
3. Internal Working
Array representation of a complete binary tree. For a node at array index i (0-indexed):
left child = 2*i + 1
right child = 2*i + 2
parent = (i - 1) / 2 (integer division)
Example Min-Heap, tree view and array view side by side:
Tree: Array index: 0 1 2 3 4 5
3 [3, 8, 5, 12, 15, 9]
/ \
8 5
/ \ /
12 15 9
Check the property: parent(3) β€ children(8,5) β; parent(8) β€ children(12,15) β; parent(5) β€ children(9) β. No sibling-to-sibling relationship is guaranteed (8 and 5 arenβt compared to each other) β this is what makes a heap βweakerβ than a fully sorted structure, and exactly why itβs cheaper to maintain.
Insertion β βbubble upβ / βsift upβ: Insert 2:
Step 1: Append at the end (last array slot):
[3, 8, 5, 12, 15, 9, 2]
β² new node, index 6, parent index (6-1)/2 = 2 β value 5
Step 2: Compare with parent (5). 2 < 5, so swap.
[3, 8, 2, 12, 15, 9, 5]
β² now at index 2, parent index (2-1)/2 = 0 β value 3
Step 3: Compare with parent (3). 2 < 3, so swap.
[2, 8, 3, 12, 15, 9, 5]
β² now at root β no parent, stop.
Deletion of the root β βbubble downβ / βsift downβ: Remove min (2) from [2, 8, 3, 12, 15, 9, 5]:
Step 1: Move the LAST element to the root, shrink the array:
[5, 8, 3, 12, 15, 9]
Step 2: Compare root (5) with children (8, 3). Swap with the SMALLER child if it violates heap property.
5 vs min(8,3)=3 β swap:
[3, 8, 5, 12, 15, 9]
Step 3: Continue sifting down from new position (index 2, value 5). Children of index 2: index 5 β value 9. 5 < 9, property holds. Stop.
Final: [3, 8, 5, 12, 15, 9]
4. Operations
Insert (push):
- Append the new element at the end of the array (next open leaf position).
- Sift up: repeatedly compare with parent; swap if the heap property is violated; stop when it holds or the root is reached.
- Edge case: inserting into an empty heap β the new element simply becomes the root, no sifting needed.
Delete (extract-min / extract-max):
- Save the root value (this is the return value).
- Move the last element in the array to the root position, shrink the array by one.
- Sift down: repeatedly compare the node with its children; swap with the smaller (min-heap) or larger (max-heap) child if the property is violated; stop when it holds or a leaf is reached.
- Edge case: deleting from a heap with one element β just remove it, no sifting needed. Deleting from an empty heap should throw/guard.
Update (increase/decrease key):
- Change the value at a given index, then sift up (if the change could violate the parent relationship) or down (if it could violate the child relationship) as appropriate. Used heavily in graph algorithms like Dijkstraβs.
Search:
- Not efficiently supported β O(n) linear scan, since the heap property gives no information about where an arbitrary value might be.
Traverse:
- Level-order (array order) is trivial β just iterate the array. In-order/sorted traversal is not naturally supported (thatβs what BSTs are for).
Peek (find-min / find-max):
- Return
array[0]. O(1) β this is the entire point of a heap.
Build-heap (from an unsorted array):
- Naively: insert each element one by one, O(n log n) total.
- Optimally: Heapify from the bottom up, starting at the last non-leaf node and sifting down each β this achieves O(n), not O(n log n) (explained in section 5).
5. Time & Space Complexity
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Peek (find min/max) | O(1) | O(1) |
| Insert | O(log n) | O(1) |
| Delete (extract min/max) | O(log n) | O(1) |
| Search (arbitrary value) | O(n) | O(1) |
| Build heap from unsorted array | O(n) | O(1) extra (in-place) |
| Heapsort (repeated extraction) | O(n log n) | O(1) extra (in-place) |
Why these hold:
- Insert/Delete are O(log n) because a complete binary tree with n nodes has height βlogβ nβ β sifting up or down traverses at most that many levels, one comparison-and-swap per level.
- Peek is O(1) because the heap property guarantees the min/max is always physically at index 0 β no search needed, by construction.
- Build-heap is O(n), not O(n log n) β this surprises most learners. The naive intuition (βn inserts Γ O(log n) each = O(n log n)β) is not how
build-heap(heapify from the bottom) works. Heapify processes nodes bottom-up, and most nodes are near the bottom where sift-down has very little distance to travel; only a few nodes near the root have far to sift. Summing this βdistance Γ count-of-nodes-at-that-distanceβ across all levels forms a series that converges to O(n) β a classic (and famous) amortized-analysis result.
6. Advantages
- O(1) access to current min/max β ideal for βalways process the most urgent itemβ workloads.
- O(log n) insert/delete β much better than maintaining a fully sorted structure.
- Compact array-backed storage β no pointer overhead, excellent cache locality compared to pointer-based trees.
- O(n) construction from an existing array via heapify.
7. Disadvantages
- No efficient search for arbitrary elements β O(n).
- No efficient traversal in sorted order (unlike a BSTβs in-order traversal).
- Only the min or max is efficiently accessible β a plain heap canβt answer βgive me the min AND max quicklyβ without extra structure (e.g., a min-max heap or two heaps).
- Not stable for equal-priority elements unless explicitly engineered (insertion order among ties isnβt preserved by default).
8. Real-World Applications
- Operating Systems: CPU process scheduling by priority (higher-priority processes run first).
- Networking: Bandwidth management / QoS β prioritizing certain packet types.
- Graph Algorithms: Dijkstraβs shortest path and Primβs MST both use a Min-Heap to always expand the βclosestβ unvisited node next.
- Databases: Top-K query optimization (e.g., βtop 10 highest-paid employeesβ) β keeping a heap of size K avoids sorting the entire dataset.
- Game Development: Event scheduling systems (process the next game event by timestamp).
- AI/ML: Beam search in NLP models often uses a heap to track the top-k most probable sequences.
- Cloud Systems / Task Queues: Job schedulers (e.g., prioritizing urgent background jobs).
- Compilers: Huffman coding (data compression) builds its tree using a Min-Heap.
Heaps are chosen anywhere βalways grab the current best/worstβ needs to happen repeatedly and efficiently, especially when the underlying data keeps changing.
9. Implementation (C++17)
#include <iostream>
#include <vector>
#include <stdexcept>
#include <algorithm>
// A Min-Heap implementation using std::vector as the backing array.
// (Flip every comparison to build a Max-Heap β see note after the class.)
class MinHeap {
private:
std::vector<int> heap;
size_t parent(size_t i) const { return (i - 1) / 2; }
size_t leftChild(size_t i) const { return 2 * i + 1; }
size_t rightChild(size_t i) const { return 2 * i + 2; }
// Sift the element at index i UP toward the root until the heap property holds.
void siftUp(size_t i) {
while (i > 0 && heap[i] < heap[parent(i)]) {
std::swap(heap[i], heap[parent(i)]);
i = parent(i);
}
}
// Sift the element at index i DOWN toward the leaves until the heap property holds.
void siftDown(size_t i) {
size_t n = heap.size();
while (true) {
size_t smallest = i;
size_t l = leftChild(i), r = rightChild(i);
if (l < n && heap[l] < heap[smallest]) smallest = l;
if (r < n && heap[r] < heap[smallest]) smallest = r;
if (smallest == i) break; // heap property restored, stop
std::swap(heap[i], heap[smallest]);
i = smallest;
}
}
public:
// Insert. O(log n): append then sift up.
void push(int value) {
heap.push_back(value);
siftUp(heap.size() - 1);
}
// Extract and return the minimum. O(log n).
int pop() {
if (heap.empty()) throw std::underflow_error("pop on empty heap");
int minValue = heap[0];
heap[0] = heap.back(); // move last element to root
heap.pop_back();
if (!heap.empty()) siftDown(0);
return minValue;
}
// Peek at the minimum without removing. O(1).
int top() const {
if (heap.empty()) throw std::underflow_error("top on empty heap");
return heap[0];
}
// Build a heap from an existing unsorted array in O(n) β NOT O(n log n).
// Key insight: start from the last non-leaf node and sift down, bottom-up.
void buildHeap(std::vector<int> arr) {
heap = std::move(arr);
int n = static_cast<int>(heap.size());
for (int i = n / 2 - 1; i >= 0; --i) { // last non-leaf index = n/2 - 1
siftDown(static_cast<size_t>(i));
}
}
bool empty() const { return heap.empty(); }
size_t size() const { return heap.size(); }
void print() const {
std::cout << "[ ";
for (int v : heap) std::cout << v << " ";
std::cout << "]\n";
}
};
// Example usage
int main() {
MinHeap h;
h.push(5);
h.push(3);
h.push(8);
h.push(1);
h.push(9);
h.print(); // array-order snapshot, e.g. [1 3 8 5 9]
std::cout << "Min: " << h.top() << "\n"; // 1
std::cout << "Extracting all in sorted order: ";
while (!h.empty()) {
std::cout << h.pop() << " "; // 1 3 5 8 9 β this IS heapsort
}
std::cout << "\n";
// Demonstrate O(n) buildHeap
MinHeap h2;
h2.buildHeap({9, 4, 7, 1, 3, 8, 2});
h2.print();
return 0;
}
/*
* TO BUILD A MAX-HEAP: flip every "<" to ">" in siftUp and siftDown
* (i.e., "heap[i] < heap[parent(i)]" becomes "heap[i] > heap[parent(i)]", and
* siftDown picks the LARGEST child instead of the smallest). Everything else β
* the index math, the array backing, the O(log n)/O(n) complexities β is identical.
* In production C++, prefer std::priority_queue<int> for Max-Heap (default) or
* std::priority_queue<int, std::vector<int>, std::greater<int>> for Min-Heap.
*/
10. Code Walkthrough
parent/leftChild/rightChildindex formulas: These three lines of arithmetic are the entire reason a heap needs no pointers β the complete-binary-tree shape guarantees these formulas always point to valid relationships, given 0-indexed array storage.siftUp: Called after appending a new element at the end. The loop conditionheap[i] < heap[parent(i)]is the heap-property check; as long as itβs violated, we swap upward. The loop naturally terminates either at the root (i == 0) or the moment the property holds.siftDown: The trickiest part β note it computessmallestby comparing the current node against both children (not just one), because in a min-heap you must swap with whichever child is smaller to correctly restore the property; swapping with the wrong child can leave a smaller value stuck below a larger one.pop(): The βmove last element to root, then sift downβ pattern is the standard heap-deletion technique. Itβs O(log n) because only the sift-down step costs anything β moving the last element is O(1).buildHeap: Starting the loop atn/2 - 1(the last non-leaf node) and going backward to 0 is what makes this O(n) rather than O(n log n) β every leaf is already trivially a valid 1-node heap, so we only need to sift down internal nodes, and we must do so bottom-up so that by the time we sift down nodei, its subtrees are already valid heaps.- Min vs Max flip: The entire class is symmetric under swapping
<for>β this symmetry is worth internalizing, since interviewers often ask you to convert one to the other on the spot.
Common mistakes to watch for here:
- Comparing only one child in
siftDowninstead of both, silently producing an invalid heap. - Forgetting to check
heap.empty()before sifting down afterpop()(sifting down an empty heap is undefined/out-of-bounds). - Using 1-indexed formulas (
2*i,2*i+1) with a 0-indexed array, or vice versa β these two conventions use different child/parent formulas and mixing them is a very common bug.
11. Dry Run
Input: push(5), push(3), push(8), push(1), push(9) on a Min-Heap.
| Step | Action | Array after | Sift trace |
|---|---|---|---|
| 1 | push(5) | [5] | no parent, no sift |
| 2 | push(3) | [3,5] | 3 < parent(5) β swap β [3,5] |
| 3 | push(8) | [3,5,8] | 8 vs parent(3): 8 > 3, stop |
| 4 | push(1) | [3,5,8,1] | 1 at idx3, parent idx1(5): 1<5 swap β [3,1,8,5]; parent idx0(3): 1<3 swap β [1,3,8,5] |
| 5 | push(9) | [1,3,8,5,9] | 9 at idx4, parent idx1(3): 9>3, stop |
Final heap array: [1, 3, 8, 5, 9] β root is 1, the true minimum. β
Now pop():
- Save root = 1 (return value).
- Move last element (9) to root:
[9, 3, 8, 5]. - Sift down from index 0: children are idx1(3), idx2(8) β smallest child is 3 (idx1). 9 > 3 β swap β
[3, 9, 8, 5]. - Continue from idx1: children are idx3(5) only (idx4 doesnβt exist) β 5 < 9 β swap β
[3, 5, 8, 9]. - Continue from idx3: no children, stop.
Result: heap becomes [3, 5, 8, 9], returned value 1. β (3 is correctly the new minimum.)
12. Interview Questions
Conceptual:
- Why is
build-heapO(n) rather than O(n log n)? Walk through the proof intuition. - Why canβt a heap efficiently support βsearch for an arbitrary valueβ?
- Compare a heap to a BST for the priority-queue use case β why is a heap usually preferred?
- Explain the difference between a Min-Heap and a Max-Heap, and how to convert between them.
- Why does a heap need to be a complete binary tree specifically (not just βbalancedβ)?
Coding:
- Implement Heapsort.
- Find the Kth largest element in an array (using a Min-Heap of size K).
- Merge K sorted lists using a Min-Heap.
- Find the median of a data stream (two heaps β one max, one min).
- Top K frequent elements.
- Implement a Min Stack or a structure supporting O(1) min/max retrieval with a heap-backed approach.
- Task Scheduler β schedule tasks with cooldowns using a Max-Heap.
Follow-ups / interviewer traps:
- βCan you find the Kth largest in better than O(n log n)?β (expects a heap of size K, giving O(n log K))
- βHow do you maintain a running median in O(log n) per insertion?β (expects two heaps β a max-heap for the lower half, min-heap for the upper half, kept balanced in size)
- βWhatβs the time complexity of
std::priority_queueβs constructor when given n elements at once?β (tests whether they know it uses O(n) heapify internally, not repeated O(log n) inserts)
13. Practice Problems
Easy
- Last Stone Weight (LeetCode 1046)
- Kth Largest Element in a Stream (LeetCode 703)
Medium
- Kth Largest Element in an Array (LeetCode 215)
- Top K Frequent Elements (LeetCode 347)
- K Closest Points to Origin (LeetCode 973)
- Task Scheduler (LeetCode 621)
- Ugly Number II (LeetCode 264)
Hard
- Merge k Sorted Lists (LeetCode 23)
- Find Median from Data Stream (LeetCode 295)
- Sliding Window Median (LeetCode 480)
- IPO / Maximize Capital (LeetCode 502)
Also recommended: GeeksforGeeks βHeapβ practice set, HackerRank βHeap, Priority Queueβ track, Codeforces problems tagged greedy + data structures that reference βalways pick the smallest/largest remaining.β
14. Common Mistakes
- Comparing only one child during sift-down instead of both, silently breaking the heap property.
- Mixing 0-indexed and 1-indexed parent/child formulas.
- Forgetting the empty-heap check before
pop()ortop(). - Assuming a heap is fully sorted β only the root is guaranteed to be the min/max; sibling order is unspecified (e.g., donβt assume
heap[1] < heap[2]). - Reinventing build-heap as repeated single inserts when a true O(n) heapify is available and expected in interviews for βgiven an array, build a heapβ questions.
- Confusing a heap with a BST β a heap gives no efficient in-order (sorted) traversal; thatβs a different structure with a different (stronger) invariant.
- Not resetting/rebalancing the two-heap technique for streaming median problems, letting one heap grow unboundedly larger than the other.
15. Summary
Key takeaways:
- A heap is a complete binary tree stored in a flat array β no pointers required, thanks to simple index arithmetic (
2i+1,2i+2,(i-1)/2). - It enforces a weak ordering (parent vs. children only) β just enough to guarantee O(1) access to the min/max, while staying cheaper to maintain than a fully sorted structure.
build-heapis a famous O(n) result β donβt default to βinsert one at a timeβ (O(n log n)) when the whole array is available upfront.- Min-Heap and Max-Heap are mirror images β the same code with comparisons flipped.
Complexity recap:
| Operation | Time | Space |
|---|---|---|
| Peek min/max | O(1) | O(1) |
| Insert | O(log n) | O(1) |
| Extract min/max | O(log n) | O(1) |
| Search arbitrary value | O(n) | O(1) |
| Build heap from array | O(n) | O(1) |
Decision guideline: Reach for a heap whenever you repeatedly need βthe current best/worst itemβ from a changing collection β priority scheduling, graph shortest-path/MST algorithms, top-K problems, or streaming statistics like running median. If you need sorted traversal or search for arbitrary elements, use a BST instead; if you only ever need the single overall min/max once (no updates), a simple linear scan is simpler and just as fast.
Next chapter: 05_hash_tables.md, or say the word for Trie, BST/AVL, or Graphs instead.
Chapter 5: Hash Tables (Hash Table, Hash Map, Hash Set)
Study time: ~6-8 hours | Prerequisite: Arrays, Linked Lists | Difficulty: Intermediate
1. Introduction
Definition: A hash table is a data structure that maps keys to values (or just stores keys, for a set) using a hash function to compute an array index from the key, giving average O(1) insert, delete, and lookup. A Hash Map is a hash table storing key-value pairs; a Hash Set is a hash table storing keys only (membership testing).
Purpose: To answer βis X present?β or βwhat value is associated with key X?β in close to constant time, regardless of how many elements are stored.
Real-world analogy: A library that assigns every book a shelf number computed directly from its ISBN (via some formula), rather than alphabetically sorting all books. To find a book, you compute the shelf number and walk straight there β no searching required, as long as two different books donβt get mapped to the exact same shelf (a βcollision,β handled in section 3).
Motivation: Arrays give O(1) access β but only by integer index. Real-world keys are strings, objects, tuples β arbitrary data. A hash function is the bridge that converts an arbitrary key into an array index, letting us reuse the arrayβs O(1) access for arbitrary key types.
History: The hashing concept dates to IBM researchers in the 1950s (Hans Peter Luhn is often credited with early hashing ideas); it became foundational to virtually every modern languageβs built-in dictionary/map type (Python dict, Java HashMap, C++ unordered_map, JavaScript Object/Map).
2. Why Do We Need It?
Problem it solves: Fast lookup/insert/delete by an arbitrary key (not necessarily a small integer), without paying the O(log n) cost of a balanced tree or the O(n) cost of linear search.
Why previous structures are insufficient:
- Array (direct indexing): only works if keys are already small, dense integers.
- Sorted array / BST: O(log n) lookup, which is good but not as fast as the O(1) average a hash table offers β and requires the key type to support ordering (
<), which isnβt always natural (e.g., is{name: "Bob"}βless thanβ{name: "Alice"}? Only if you define an ordering β a hash table needs no such definition). - Linked list: O(n) β no better than brute-force search.
Trade-offs:
- You gain O(1) average-case operations for arbitrary key types.
- You pay for it with: no ordering (canβt easily ask βgive me keys in sorted orderβ or βgive me the next key after Xβ), worst-case O(n) if hashing goes badly (many collisions), and memory overhead (unused buckets, plus collision-handling structures).
3. Internal Working
Step 1 β Hash function: Converts a key into an integer, then that integer is reduced to a valid array index via modulo:
index = hash(key) % table_size
Example with a simple string hash and table_size = 7:
hash("cat") = 312 β 312 % 7 = 4 β bucket 4
hash("dog") = 205 β 205 % 7 = 2 β bucket 2
Step 2 β Collisions. Two different keys can hash to the same bucket. Two standard strategies:
(a) Chaining β each bucket holds a linked list (or small vector) of all key-value pairs that hashed there:
Bucket 0: []
Bucket 1: []
Bucket 2: [("dog", 5)]
Bucket 3: []
Bucket 4: [("cat", 9)] β [("bat", 2)] β collision! both hashed to 4, chained together
Bucket 5: []
Bucket 6: []
To find "bat": compute hash("bat") % 7 = 4, go to bucket 4, then linearly scan the short chain ("cat" β no match, "bat" β match, return 2).
(b) Open Addressing (linear probing) β no chains; if a bucket is occupied, probe the next slot until an empty one is found:
Insert "cat" β bucket 4 (empty) β place there.
Insert "bat" β bucket 4 (occupied by "cat") β probe bucket 5 (empty) β place there.
Lookup for "bat" must replay the same probing sequence: check bucket 4 (occupied, but not a match) β check bucket 5 (match).
Step 3 β Resizing (rehashing). When the table gets too full (measured by load factor = n / table_size, typically resized when it exceeds ~0.7), a bigger table is allocated and every existing key is re-hashed into the new table (since % table_size changes with the new size). This is the O(n) event that amortizes into O(1) average, exactly like a dynamic arrayβs resize.
4. Operations
Insert (put):
- Compute
hash(key) % table_size. - Chaining: append to the bucketβs list (or update if key already exists in the chain).
- Open addressing: probe forward until an empty (or matching) slot is found.
- If load factor exceeds threshold, trigger a resize + full rehash.
- Edge case: inserting a duplicate key should update the value, not create a second entry.
Delete:
- Compute the bucket, then find and remove the matching key.
- Chaining: remove the node from the linked list. O(1) average (short chain).
- Open addressing: trickier β simply clearing the slot can break the probing sequence for other keys that probed past it. Requires either a βtombstoneβ marker or shifting subsequent entries back.
Search (get / contains):
- Compute the bucket, then scan the chain (chaining) or probe forward (open addressing) until the key is found or an empty slot is hit (meaning βnot presentβ).
Update:
- Same as insert for an existing key β locate the bucket/chain entry and overwrite the value.
Traverse:
- Iterate all buckets and all entries within each. O(n), but in no particular order (unlike arrays/trees).
5. Time & Space Complexity
| Operation | Average Case | Worst Case | Space Complexity |
|---|---|---|---|
| Insert | O(1) | O(n) | O(n) |
| Delete | O(1) | O(n) | O(1) |
| Search | O(1) | O(n) | O(1) |
| Traverse all | O(n) | O(n) | O(1) extra |
| Resize (amortized per insert) | O(1) amortized | O(n) for the resize event itself | O(n) |
Why these hold:
- Average O(1) assumes a good hash function that spreads keys roughly uniformly across buckets, keeping each bucketβs chain short (ideally length ~load factor, a small constant).
- Worst case O(n) happens when many/all keys collide into the same bucket (e.g., a poor hash function, or an adversary crafting colliding keys) β the chain degenerates into a plain linked list, and search becomes linear.
- Resizing is O(n) for that single operation (every key must be rehashed), but because resizes happen exponentially less often as the table doubles, the amortized cost per insert stays O(1) β the same geometric-series argument as the Dynamic Array chapter.
6. Advantages
- O(1) average time for insert/search/delete β often the fastest general-purpose lookup structure available.
- Works with any hashable key type β strings, tuples, custom objects (given a proper hash function).
- Simple mental model once you understand hash + bucket + collision handling.
7. Disadvantages
- No ordering β canβt efficiently get βsorted keysβ or βthe next key after Xβ (a BST/sorted structure is needed for that).
- Worst-case O(n) if the hash function is poor or under adversarial input (hash-flooding attacks β a real security concern for public-facing services).
- Memory overhead: some buckets stay empty (chaining) or a resize must maintain headroom (open addressing) to keep load factor low.
- Iteration order is unspecified and can change between runs/insertions (unlike an array or linked list).
8. Real-World Applications
- Databases: Indexing (hash indexes) for equality lookups; in-memory caches (e.g., Redis is fundamentally a giant distributed hash map).
- Compilers: Symbol tables mapping variable/function names to their metadata.
- Operating Systems: Page tables (mapping virtual to physical memory addresses) often use hashing structures.
- Networking: Routing tables, DNS caching (domain name β IP address lookups).
- Search Engines: Deduplication of crawled URLs (hash set of visited pages).
- Browsers: The
Object/Maptypes in JavaScript are hash tables under the hood. - Security: Password storage (hashed, not the table structure itself, but the underlying hash function concept), rate-limiting (hash set of recent request IDs).
- AI/ML: Feature hashing (βthe hashing trickβ) to map huge vocabularies into fixed-size feature vectors.
9. Implementation (C++17)
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <stdexcept>
// A HashMap<string, int> implemented with separate chaining.
// Demonstrates: hash function, bucket array, collision handling, and resizing.
class HashMap {
private:
struct Entry {
std::string key;
int value;
};
std::vector<std::list<Entry>> buckets; // each bucket is a chain (linked list)
size_t count; // total number of key-value pairs stored
static constexpr double MAX_LOAD_FACTOR = 0.7;
// A simple polynomial rolling hash (djb2-style) for strings.
size_t hashKey(const std::string& key) const {
size_t hash = 5381;
for (char c : key) {
hash = hash * 33 + static_cast<size_t>(c);
}
return hash;
}
size_t bucketIndex(const std::string& key) const {
return hashKey(key) % buckets.size();
}
// Rehash everything into a table of double the size when load factor is exceeded.
void resize() {
std::vector<std::list<Entry>> oldBuckets = std::move(buckets);
buckets = std::vector<std::list<Entry>>(oldBuckets.size() * 2);
for (auto& chain : oldBuckets) {
for (auto& entry : chain) {
size_t idx = bucketIndex(entry.key); // recompute index for NEW table size
buckets[idx].push_back(entry);
}
}
}
public:
HashMap() : buckets(8), count(0) {} // start with 8 buckets
// Insert or update. Amortized O(1).
void put(const std::string& key, int value) {
double loadFactor = static_cast<double>(count + 1) / buckets.size();
if (loadFactor > MAX_LOAD_FACTOR) {
resize();
}
size_t idx = bucketIndex(key);
for (auto& entry : buckets[idx]) {
if (entry.key == key) { // key already exists β update in place
entry.value = value;
return;
}
}
buckets[idx].push_back({key, value}); // new key β append to chain
count++;
}
// Search. Average O(1), worst O(n) if a chain is long.
bool get(const std::string& key, int& outValue) const {
size_t idx = bucketIndex(key);
for (const auto& entry : buckets[idx]) {
if (entry.key == key) {
outValue = entry.value;
return true;
}
}
return false; // key not found
}
// Delete. Average O(1).
bool remove(const std::string& key) {
size_t idx = bucketIndex(key);
auto& chain = buckets[idx];
for (auto it = chain.begin(); it != chain.end(); ++it) {
if (it->key == key) {
chain.erase(it);
count--;
return true;
}
}
return false;
}
bool contains(const std::string& key) const {
int dummy;
return get(key, dummy);
}
size_t size() const { return count; }
};
// Example usage
int main() {
HashMap map;
map.put("apple", 3);
map.put("banana", 7);
map.put("cherry", 12);
int value;
if (map.get("banana", value)) {
std::cout << "banana -> " << value << "\n"; // 7
}
map.put("banana", 20); // update existing key
map.get("banana", value);
std::cout << "banana updated -> " << value << "\n"; // 20
map.remove("apple");
std::cout << "Contains apple? " << (map.contains("apple") ? "yes" : "no") << "\n"; // no
std::cout << "Map size: " << map.size() << "\n"; // 2
return 0;
}
10. Code Walkthrough
hashKey: A djb2-style polynomial hash β multiply-and-add across each character. The specific constants (5381, 33) are well-known choices that empirically spread string hashes well; the important concept is that it deterministically turns any string into a large integer.bucketIndex: Reduces the (potentially huge) hash value into a valid array index via modulo. This is the step that actually connects βarbitrary keyβ to βarray position.βbucketsasvector<list<Entry>>: Each bucket is a chain β this is separate chaining. Usingstd::listmeans O(1) removal given an iterator, and no shifting needed on delete (unlike an array-backed chain).resize(): Note that every entry must be re-bucketed, not just copied βbucketIndexdepends onbuckets.size(), so an entry that hashed to bucket 3 in an 8-bucket table might belong in bucket 11 in a 16-bucket table. This full rehash is the O(n) cost that amortizes.put(): Checks load factor before inserting (usingcount + 1to see if the new count would exceed threshold) β this ordering avoids ever exceeding the threshold even briefly.get()/remove(): Both walk the target bucketβs chain linearly β this is the O(1)-average-but-O(n)-worst-case part: if the hash function is bad and everything collides into one bucket, these become full linear scans.
Common mistakes to watch for here:
- Forgetting to re-bucket (only copying, not rehashing) during resize β this silently corrupts lookups since old bucket indices are invalid for the new table size.
- Using a poor hash function (e.g., just the stringβs length) β causes massive collision clustering.
- Not handling key updates (
puton an existing key) β accidentally creating duplicate entries instead of updating in place.
11. Dry Run
Setup: 8 buckets. Assume (for illustration) simplified hash values: hash("apple")=101, hash("banana")=205, hash("cherry")=308, all mod 8.
| Key | hash % 8 | Bucket |
|---|---|---|
| apple | 101 % 8 = 5 | 5 |
| banana | 205 % 8 = 5 | 5 (collision with apple!) |
| cherry | 308 % 8 = 4 | 4 |
Insert sequence: put("apple",3), put("banana",7), put("cherry",12)
| Step | Bucket 4 | Bucket 5 |
|---|---|---|
| after apple | [] | [(βappleβ,3)] |
| after banana | [] | [(βappleβ,3) β (βbananaβ,7)] β chained due to collision |
| after cherry | [(βcherryβ,12)] | [(βappleβ,3) β (βbananaβ,7)] |
get("banana"): compute bucket 5 β scan chain: "apple" (no match) β "banana" (match) β return 7. Two comparisons β still fast, but this illustrates why worst-case degrades: if 1000 keys collided into bucket 5, this scan would be O(1000).
12. Interview Questions
Conceptual:
- Explain how a hash table achieves O(1) average lookup, and when it degrades to O(n).
- Compare chaining vs. open addressing for collision handling β trade-offs of each.
- What makes a βgoodβ hash function? What happens with a bad one?
- Why does resizing (rehashing) need to touch every existing key, not just the new one?
- Why canβt a hash table efficiently support βgive me the smallest keyβ the way a BST or heap can?
Coding:
- Design a HashMap from scratch (no built-in map/dict).
- Group Anagrams using a hash map.
- Two Sum using a hash map (O(n) instead of O(nΒ²)).
- Longest Consecutive Sequence using a hash set.
- LRU Cache (hash map + doubly linked list β full chapter later).
- First Unique Character in a string.
- Subarray Sum Equals K (prefix sum + hash map).
Follow-ups / interviewer traps:
- βWhat if the hash function isnβt uniform β how does that affect complexity?β (tests worst-case understanding)
- βCan you design a hash table where deletion doesnβt break open-addressing probing?β (expects tombstones or backward-shift deletion)
- βHow would you handle hash-flooding attacks in a public API?β (tests security awareness β randomized/keyed hash functions)
13. Practice Problems
Easy
- Two Sum (LeetCode 1)
- Contains Duplicate (LeetCode 217)
- Valid Anagram (LeetCode 242)
- Ransom Note (LeetCode 383)
Medium
- Group Anagrams (LeetCode 49)
- Top K Frequent Elements (LeetCode 347) β combines hashing + heap
- Longest Consecutive Sequence (LeetCode 128)
- Subarray Sum Equals K (LeetCode 560)
- Design HashMap (LeetCode 706)
Hard
- LRU Cache (LeetCode 146)
- Insert Delete GetRandom O(1) (LeetCode 380)
- Substring with Concatenation of All Words (LeetCode 30)
Also recommended: GeeksforGeeks βHashingβ practice set, HackerRank βDictionaries and Hashmapsβ track.
14. Common Mistakes
- Assuming O(1) is guaranteed, not average-case β forgetting worst-case O(n) exists under bad hashing/collisions.
- Using a mutable object as a key without understanding that if its hash changes after insertion, it becomes unfindable (a subtle bug in many languages).
- Not rehashing fully on resize β only copying without recomputing bucket indices.
- Iterating and expecting sorted or insertion order β hash table iteration order is unspecified (use an ordered map/tree, or a supplementary list, if order matters).
- Ignoring load factor β never resizing leads to long chains and degraded performance over time.
- Comparing hash values directly for equality instead of comparing the actual keys (two different keys can share a hash β always verify with a full key comparison after narrowing to a bucket).
15. Summary
Key takeaways:
- A hash table converts an arbitrary key into an array index via a hash function, giving average O(1) operations at the cost of losing ordering.
- Collisions are inevitable (pigeonhole principle) and must be handled β chaining (simple, extra memory) or open addressing (compact, trickier deletion).
- Resizing/rehashing is what keeps average-case O(1) sustainable as the table grows β same amortization principle as dynamic arrays.
Complexity recap:
| Operation | Average | Worst |
|---|---|---|
| Insert | O(1) | O(n) |
| Search | O(1) | O(n) |
| Delete | O(1) | O(n) |
Decision guideline: Choose a hash table when you need the fastest possible key-based lookup and donβt care about ordering. Choose a BST/ordered map instead if you need sorted iteration, range queries, or βnext/previous keyβ operations.
Next chapter: 06_binary_tree_and_bst.md
Chapter 6: Binary Tree & Binary Search Tree (BST)
Study time: ~7-9 hours | Prerequisite: Recursion, Linked Lists | Difficulty: Intermediate
1. Introduction
Definition: A Binary Tree is a hierarchical structure where each node has at most two children, referred to as left and right. A Binary Search Tree (BST) is a binary tree with an added ordering invariant: for every node, all values in its left subtree are smaller, and all values in its right subtree are larger.
Purpose: Binary trees model hierarchical relationships (file systems, org charts, decision processes). BSTs specifically add the ability to search, insert, and delete in O(log n) while keeping data in sorted order β something neither arrays (O(log n) search but O(n) insert) nor hash tables (O(1) but unordered) can do simultaneously.
Real-world analogy: A BST is like a well-organized filing cabinet where, at each drawer, a label tells you βeverything before M is to the left, everything after M is to the right.β You can find any file by repeatedly halving your search space β never opening every drawer.
Motivation: We want the sorted-order benefits of a sorted array (in-order traversal, range queries, βfind next larger valueβ) combined with the fast-insert/delete benefits of a linked structure. A BST achieves both β as long as it stays reasonably balanced (which motivates the AVL Tree in the next chapter).
History: BSTs emerged from 1960s work formalizing efficient search structures; they underpin the C++ std::map/std::set (technically Red-Black Trees, a BST variant) and database indexing structures.
2. Why Do We Need It?
Problem it solves: Maintaining data in sorted order while supporting O(log n) search, insert, and delete β and enabling range queries (βall values between 10 and 50β) and ordered traversal, which hash tables cannot do.
Why previous structures are insufficient:
- Sorted array: O(log n) search via binary search, but O(n) insert/delete (must shift elements).
- Hash table: O(1) average search, but no ordering β canβt do range queries or βnext greater elementβ efficiently.
- Linked list: O(n) for everything.
Trade-offs:
- You gain O(log n) (average case, assuming reasonable balance) for search/insert/delete plus sorted-order traversal and range queries.
- You pay for it with O(n) worst case if the tree becomes skewed (e.g., inserting sorted data one at a time turns it into a degenerate linked list), and extra memory for two pointers per node.
3. Internal Working
A valid BST:
50
/ \
30 70
/ \ / \
20 40 60 80
Check: everything left of 50 (30,20,40) is < 50; everything right (70,60,80) is > 50. This holds recursively at every subtree β 20 < 30 < 40, 60 < 70 < 80.
Node structure (pointer-based):
struct Node {
int data;
Node* left;
Node* right;
};
Search for 60, step by step:
Start at root (50). 60 > 50 β go right.
At 70. 60 < 70 β go left.
At 60. Match! Found.
Three comparisons to find one node among seven β this is the O(log n) behavior: each comparison eliminates roughly half the remaining nodes.
Insertion of 45:
Start at root (50). 45 < 50 β go left.
At 30. 45 > 30 β go right.
At 40. 45 > 40 β go right, but 40 has no right child β insert here.
Result:
50
/ \
30 70
/ \ / \
20 40 60 80
\
45
Deletion β the tricky case (deleting a node with two children): To delete 30 (which has children 20 and 40), you canβt just remove it β youβd orphan both children. The standard technique: replace 30βs value with its in-order successor (the smallest value in its right subtree β here, 40, since 30βs right subtree is just {40}), then delete that successor node from its original position (which is now guaranteed to have at most one child).
Before deleting 30: After replacing 30's value with 40, then removing the original 40 node:
30 40
/ \ / \
20 40 20 (nothing β original 40 had no children, simply removed)
In-order traversal (Left β Node β Right) β the traversal that visits nodes in sorted order, which is the defining useful property of a BST:
Traversing the tree above: 20, 30, 40, 45, 50, 60, 70, 80 β sorted!
4. Operations
Insert:
- Start at root; at each node, go left if the new value is smaller, right if larger.
- When you reach a NULL pointer, place the new node there.
- Edge case: inserting a duplicate β convention varies (reject, count, or allow as right child); must be decided upfront and applied consistently.
- Worst case O(n) if the tree is skewed (e.g., inserting 1,2,3,4,5 in order creates a tree thatβs really just a linked list leaning right).
Delete:
- Leaf node (no children): simply remove it.
- One child: replace the node with its single child.
- Two children: replace the nodeβs value with its in-order successor (or predecessor), then delete that successor node (which now has at most one child, reducing to a simpler case).
Search:
- Compare target with current node; go left if smaller, right if larger, until found or a NULL is hit (not present).
Update:
- Typically implemented as delete + insert (changing a nodeβs value in place could violate the BST property if not done carefully).
Traverse:
- In-order (Left, Node, Right): sorted order.
- Pre-order (Node, Left, Right): useful for copying/serializing a tree.
- Post-order (Left, Right, Node): useful for safely deleting a tree (children before parent).
- Level-order (BFS, using a Queue): useful for visualizing tree shape level by level.
Peek (find min/max):
- Min: follow left pointers until NULL. Max: follow right pointers until NULL. O(h) where h is tree height.
5. Time & Space Complexity
| Operation | Average (Balanced) | Worst (Skewed) | Space Complexity |
|---|---|---|---|
| Search | O(log n) | O(n) | O(1) iterative, O(h) recursive (call stack) |
| Insert | O(log n) | O(n) | O(1) iterative, O(h) recursive |
| Delete | O(log n) | O(n) | O(1) iterative, O(h) recursive |
| Find min/max | O(log n) | O(n) | O(1) |
| In-order traversal (full) | O(n) | O(n) | O(h) for recursion stack |
Why these hold:
- A balanced BST has height h β logβ(n), since each level can hold up to twice as many nodes as the level above β so n nodes require only about logβ(n) levels, and every search/insert/delete walks at most one path from root to a leaf (length = height).
- A skewed tree (e.g., built by inserting already-sorted data) degenerates toward a linked list with height β n, making every operation O(n) β this single fact is the entire motivation for the AVL Tree (next chapter), which guarantees balance.
- Traversal is always O(n) because every node must be visited exactly once, regardless of tree shape.
6. Advantages
- Maintains sorted order automatically β in-order traversal gives sorted output βfor free.β
- O(log n) search/insert/delete when balanced β the best of both sorted-array and linked-list worlds.
- Supports range queries and βnext greater/smallerβ operations naturally.
- Flexible size β grows/shrinks node by node, no bulk reallocation.
7. Disadvantages
- No balance guarantee by default β a naive BST can degrade to O(n) with unlucky/adversarial insert order.
- More complex deletion logic than simpler structures (three distinct cases to handle).
- Pointer-based nodes mean extra memory overhead and worse cache locality compared to array-backed structures.
- Recursive implementations risk stack overflow on very deep/skewed trees.
8. Real-World Applications
- Databases: Index structures (though production databases typically use B-Trees, a generalization covered in Chapter 8, optimized for disk I/O).
- File Systems: Directory structures are naturally tree-shaped; some indexing structures use BST-like designs.
- Compilers: Abstract Syntax Trees (ASTs) representing parsed code are binary/n-ary trees; expression trees for evaluating arithmetic.
- Networking: IP routing tables sometimes use tree structures for prefix matching.
- AI/ML: Decision trees (a generalization to n-ary, but rooted in the same recursive-partitioning idea) for classification/regression.
- Standard Libraries:
std::map/std::setin C++ andTreeMap/TreeSetin Java are (self-balancing) BSTs under the hood. - Game Development: Spatial partitioning (though k-d trees / quad-trees, generalizations of BSTs to multiple dimensions, are more common there).
9. Implementation (C++17)
#include <iostream>
#include <memory>
#include <vector>
// A Binary Search Tree using smart pointers for automatic memory management.
class BST {
private:
struct Node {
int data;
std::unique_ptr<Node> left;
std::unique_ptr<Node> right;
Node(int val) : data(val), left(nullptr), right(nullptr) {}
};
std::unique_ptr<Node> root;
// Recursive helper for insertion. Returns the (possibly new) subtree root.
std::unique_ptr<Node> insertHelper(std::unique_ptr<Node> node, int value) {
if (!node) {
return std::make_unique<Node>(value); // found the insertion point
}
if (value < node->data) {
node->left = insertHelper(std::move(node->left), value);
} else if (value > node->data) {
node->right = insertHelper(std::move(node->right), value);
}
// if value == node->data, we silently ignore duplicates (a design choice)
return node;
}
// Recursive helper for deletion. Returns the (possibly new) subtree root.
std::unique_ptr<Node> deleteHelper(std::unique_ptr<Node> node, int value) {
if (!node) return nullptr; // value not found, nothing to do
if (value < node->data) {
node->left = deleteHelper(std::move(node->left), value);
} else if (value > node->data) {
node->right = deleteHelper(std::move(node->right), value);
} else {
// Found the node to delete.
if (!node->left) return std::move(node->right); // 0 or 1 child (right)
if (!node->right) return std::move(node->left); // 1 child (left)
// Two children: find in-order successor (leftmost node of right subtree).
Node* successor = node->right.get();
while (successor->left) successor = successor->left.get();
node->data = successor->data; // copy successor's value up
node->right = deleteHelper(std::move(node->right), successor->data); // remove the duplicate
}
return node;
}
void inOrderHelper(const Node* node, std::vector<int>& result) const {
if (!node) return;
inOrderHelper(node->left.get(), result);
result.push_back(node->data);
inOrderHelper(node->right.get(), result);
}
const Node* searchHelper(const Node* node, int value) const {
if (!node || node->data == value) return node;
return value < node->data ? searchHelper(node->left.get(), value)
: searchHelper(node->right.get(), value);
}
public:
BST() : root(nullptr) {}
// Insert. O(log n) average, O(n) worst (skewed tree).
void insert(int value) {
root = insertHelper(std::move(root), value);
}
// Delete. O(log n) average, O(n) worst.
void remove(int value) {
root = deleteHelper(std::move(root), value);
}
// Search. O(log n) average, O(n) worst.
bool contains(int value) const {
return searchHelper(root.get(), value) != nullptr;
}
// In-order traversal returns elements in SORTED order β the defining BST property.
std::vector<int> inOrder() const {
std::vector<int> result;
inOrderHelper(root.get(), result);
return result;
}
// Find minimum value. O(log n) average.
int findMin() const {
const Node* current = root.get();
while (current->left) current = current->left.get();
return current->data;
}
};
// Example usage
int main() {
BST tree;
for (int v : {50, 30, 70, 20, 40, 60, 80}) {
tree.insert(v);
}
std::cout << "In-order (sorted): ";
for (int v : tree.inOrder()) std::cout << v << " ";
std::cout << "\n"; // 20 30 40 50 60 70 80
std::cout << "Contains 60? " << (tree.contains(60) ? "yes" : "no") << "\n"; // yes
std::cout << "Min value: " << tree.findMin() << "\n"; // 20
tree.remove(30); // two-children deletion case
std::cout << "After deleting 30: ";
for (int v : tree.inOrder()) std::cout << v << " ";
std::cout << "\n"; // 20 40 50 60 70 80
return 0;
}
10. Code Walkthrough
std::unique_ptr<Node>: Using smart pointers means we never manuallydeleteβ when aunique_ptrgoes out of scope (e.g., a subtree is replaced), its destructor recursively frees the whole subtree automatically. This eliminates an entire class of memory-leak bugs common in raw-pointer BST implementations.insertHelperβs βreturn the subtree rootβ pattern: Rather than tracking parent pointers, each recursive call returns what the subtree root should be after the operation, and the caller reattaches it (node->left = insertHelper(std::move(node->left), value)). This functional style avoids a whole category of βdid I update the parentβs pointer correctly?β bugs.deleteHelperβs three cases: No children and one child are actually the same code path here (!node->leftreturnsnode->right, which isnullptrif thereβs truly no child) β a neat simplification. The two-children case is the only one requiring extra work: find the in-order successor (leftmost node of the right subtree β guaranteed to have no left child), copy its value up, then recursively delete the now-duplicate successor from its original position.std::move(node->left): Required becauseunique_ptrcanβt be copied β ownership must be explicitly transferred into the recursive call, and the functionβs return value transfers it back.searchHelper: A clean ternary-based recursive binary search β notice itβs structurally identical to array-based binary search, just navigating pointers instead of array indices.
Common mistakes to watch for here:
- Forgetting to reattach the result of
insertHelper/deleteHelperto the parentβs pointer β this silently drops the change. - In deletion, deleting the found successor node incorrectly instead of the duplicate now sitting in its original position, corrupting the tree.
- Assuming deletion is O(log n) worst case β itβs O(log n) only if the tree is balanced; a skewed BST makes it O(n), same as search/insert.
11. Dry Run
Insert sequence: 50, 30, 70, 20, 40, 60, 80 (as in the example tree above). Each insertion follows the βcompare and go left/right until NULLβ path shown in section 3.
Now remove(30) (two children: 20 and 40):
| Step | Action |
|---|---|
| 1 | Search reaches node 30 β matches target. |
| 2 | 30 has both left (20) and right (40) children β two-children case. |
| 3 | Find in-order successor: go right to 40, then check its left β none, so 40 IS the successor. |
| 4 | Copy successorβs value (40) into node 30βs data field β node now holds value 40. |
| 5 | Recursively delete the original β40β node from the right subtree β it has no children, so itβs simply removed. |
Resulting tree:
50
/ \
40 70
/ / \
20 60 80
In-order traversal check: 20, 40, 50, 60, 70, 80 β still sorted. β
12. Interview Questions
Conceptual:
- Why does a BST degrade to O(n) when built from already-sorted input?
- Explain the three deletion cases (no child, one child, two children) and why the two-children case needs an in-order successor/predecessor.
- Whatβs the difference between in-order, pre-order, post-order, and level-order traversal, and when would you use each?
- Why is
std::mapin C++ typically a Red-Black Tree rather than a plain BST? - How would you check if a given binary tree is a valid BST?
Coding:
- Validate whether a binary tree is a valid BST.
- Find the Lowest Common Ancestor (LCA) of two nodes in a BST.
- Convert a sorted array into a balanced BST.
- Find the Kth smallest element in a BST.
- Serialize and deserialize a binary tree.
- Check if two binary trees are identical / symmetric.
- Find the in-order successor of a given node.
Follow-ups / interviewer traps:
- βCan you validate a BST in O(n) with O(1) extra space (no recursion, no array)?β (expects Morris traversal or careful iterative in-order with bounds tracking)
- βWhat if the BST allows duplicates β does your LCA/traversal logic still work?β (tests edge-case robustness)
- βYour delete function β whatβs its worst-case time complexity, and when does that worst case occur?β (tests whether they conflate average and worst case)
13. Practice Problems
Easy
- Invert Binary Tree (LeetCode 226)
- Maximum Depth of Binary Tree (LeetCode 104)
- Same Tree (LeetCode 100)
- Search in a Binary Search Tree (LeetCode 700)
Medium
- Validate Binary Search Tree (LeetCode 98)
- Lowest Common Ancestor of a BST (LeetCode 235)
- Kth Smallest Element in a BST (LeetCode 230)
- Delete Node in a BST (LeetCode 450)
- Binary Tree Level Order Traversal (LeetCode 102)
Hard
- Serialize and Deserialize Binary Tree (LeetCode 297)
- Recover Binary Search Tree (LeetCode 99)
- Binary Tree Maximum Path Sum (LeetCode 124)
Also recommended: GeeksforGeeks βBinary Search Treeβ practice set, HackerRank βTreesβ track.
14. Common Mistakes
- Not reattaching pointers after recursive insert/delete calls, silently losing changes.
- Confusing average and worst case β assuming O(log n) always holds without considering tree balance.
- Mishandling the two-children deletion case β deleting the wrong node or forgetting to copy the successorβs value up first.
- Off-by-one / wrong comparison direction β going right when you meant left (swapping the BST invariant accidentally).
- Recursive stack overflow on deep/skewed trees for very large n β an iterative approach or self-balancing tree avoids this.
- Forgetting duplicate-handling policy β inconsistent duplicate handling (sometimes inserting left, sometimes right) can silently break the BST invariant.
15. Summary
Key takeaways:
- A BST combines sorted-order maintenance with O(log n) operations β but only when balanced; an unbalanced BST is no better than a linked list.
- In-order traversal is the βfreeβ benefit that unlocks sorted iteration, range queries, and βnext/previousβ operations that hash tables cannot offer.
- Deletionβs two-children case (in-order successor/predecessor) is the trickiest part and a very common interview probe point.
- The BSTβs Achillesβ heel β no balance guarantee β is exactly what the next chapter (AVL Tree) fixes.
Complexity recap:
| Average (balanced) | Worst (skewed) | |
|---|---|---|
| Search / Insert / Delete | O(log n) | O(n) |
| Traversal (any type) | O(n) | O(n) |
Decision guideline: Use a BST when you need sorted-order maintenance with reasonably fast search/insert/delete, and you can either control insertion order (avoiding worst-case skew) or youβll use a self-balancing variant. If you donβt need ordering, a Hash Table is faster on average; if you need guaranteed worst-case O(log n), use an AVL or Red-Black Tree (next chapter).
Next chapter: 07_avl_tree.md
Chapter 7: AVL Tree
Study time: ~7-9 hours | Prerequisite: Binary Search Tree | Difficulty: Intermediate-Advanced
1. Introduction
Definition: An AVL Tree (named after inventors Adelson-Velsky and Landis) is a self-balancing Binary Search Tree where, for every node, the heights of its left and right subtrees differ by at most 1. This difference is called the balance factor. Whenever an insertion or deletion would violate this rule, the tree performs rotations to restore balance.
Purpose: To guarantee O(log n) search, insert, and delete β closing the exact loophole a plain BST has (worst-case O(n) when skewed).
Real-world analogy: Imagine a mobile (the hanging kind above a babyβs crib) β it must stay roughly balanced or it tips over. An AVL Tree is constantly βre-adjusting its hanging armsβ (via rotations) after every insert/delete so no branch ever grows dramatically longer than its sibling.
Motivation: A plain BSTβs performance depends entirely on insertion order β insert sorted data and you get a linked list in disguise. Real applications canβt gamble on βhopefully the input order is nice.β AVL trees remove that gamble with a hard mathematical guarantee.
History: Introduced in 1962 β the first self-balancing binary search tree ever published, predating Red-Black Trees (1972) by a decade.
2. Why Do We Need It?
Problem it solves: Guaranteeing O(log n) height (and therefore O(log n) operations) regardless of insertion order β eliminating the plain BSTβs worst-case vulnerability.
Why a plain BST is insufficient: As shown in Chapter 6, inserting already-sorted data into a plain BST produces a completely skewed, linked-list-shaped tree β O(n) for every operation. Many real datasets are sorted or near-sorted (timestamps, IDs), making this failure mode common, not theoretical.
Trade-offs:
- You gain a mathematically guaranteed O(log n) for search, insert, and delete, no matter the input order.
- You pay for it with extra bookkeeping (storing/maintaining height at every node) and more work per insert/delete (potential rotations), making AVL trees somewhat slower in practice for write-heavy workloads than a looser structure like a Red-Black Tree (which tolerates more imbalance in exchange for fewer rotations).
3. Internal Working
Balance Factor = height(left subtree) β height(right subtree). Valid values: -1, 0, +1. Anything else triggers rebalancing.
The four imbalance cases and their fixes:
Case 1 β Left-Left (LL): New node inserted into the left subtree of the left child.
30 20
/ / \
20 rotate 10 30
/ RIGHT
10 at 30
Fix: single right rotation at the unbalanced node.
Case 2 β Right-Right (RR): Mirror image of LL.
10 20
\ / \
20 rotate 10 30
\ LEFT
30 at 10
Fix: single left rotation.
Case 3 β Left-Right (LR): New node inserted into the right subtree of the left child.
30 30 20
/ / / \
10 rotate 20 rotate 10 30
\ LEFT / RIGHT
20 at 10 10 at 30
Fix: left rotation at the child, then right rotation at the node β a two-step (βzig-zagβ) fix.
Case 4 β Right-Left (RL): Mirror image of LR β right rotation at the child, then left rotation at the node.
Right rotation, mechanically (the core building block):
Before: After right-rotating at y:
y x
/ \ / \
x C A y
/ \ / \
A B B C
x becomes the new subtree root; y becomes xβs right child; xβs old right child (B) becomes yβs new left child (since B is still βbetweenβ A and y in sorted order β this reassignment is what preserves the BST property through the rotation).
After every insert/delete, the algorithm walks back up from the insertion/deletion point to the root, updating heights and checking the balance factor at each ancestor β this is why rotations are needed only along a single root-to-node path, not throughout the whole tree.
4. Operations
Insert:
- Perform a standard BST insert (as in Chapter 6).
- Walk back up the path to the root, updating each ancestorβs height.
- At each ancestor, compute the balance factor; if itβs outside [-1, +1], identify which of the four cases (LL, RR, LR, RL) applies (based on which side is heavier and where the newest node landed), and apply the corresponding rotation(s).
- At most O(log n) rotations are needed per insert (bounded by tree height), though in practice often just one.
Delete:
- Perform a standard BST delete (as in Chapter 6, including the in-order-successor technique for two-children nodes).
- Walk back up from the deletion point, updating heights and rebalancing exactly as in insert.
- Unlike insertion, a single deletion can require rebalancing at multiple ancestors on the way up (though still bounded by O(log n) total).
Search:
- Identical to plain BST search β the only reason itβs guaranteed O(log n) here is the height guarantee; the search algorithm itself doesnβt change at all.
Update:
- As with plain BST, typically delete + insert to avoid violating the BST property mid-update.
Traverse:
- Identical to plain BST β in-order gives sorted order, etc.
5. Time & Space Complexity
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Search | O(log n) β guaranteed | O(1) iterative, O(log n) recursive |
| Insert | O(log n) β guaranteed | O(log n) recursion stack |
| Delete | O(log n) β guaranteed | O(log n) recursion stack |
| Rotation (single) | O(1) | O(1) |
| Height/balance-factor update | O(1) per node | O(1) |
Why these hold:
- The AVL balance invariant mathematically guarantees the treeβs height is always O(log n) β specifically, it can be proven that an AVL tree with n nodes has height at most β1.44 logβ(n), a constant factor away from the theoretical minimum. This is the fact that makes every operationβs O(log n) bound a guarantee, not just an average case.
- Each individual rotation is O(1) β it only touches a small, fixed number of pointers (as shown in section 3), regardless of subtree size.
- Insert triggers at most one rebalancing rotation sequence (though it can be a double rotation, still O(1)); delete can require rebalancing at multiple levels on the path back to root, but that path has length O(log n), so total rebalancing work per delete is still O(log n).
6. Advantages
- Guaranteed O(log n) for search, insert, delete β no adversarial input can degrade it, unlike a plain BST.
- Stricter balance than a Red-Black Tree means faster lookups (shorter average path length) β ideal for read-heavy workloads.
- Conceptually simpler rotation logic than some alternatives (only 4 cases, well-documented).
7. Disadvantages
- More rotations on average during insert/delete than a Red-Black Tree (which tolerates looser balance), making AVL trees comparatively slower for write-heavy workloads.
- Extra memory per node to store height (or balance factor).
- More complex to implement correctly than a plain BST β four distinct rebalancing cases to get right.
8. Real-World Applications
- Databases: Some in-memory indexing structures use AVL trees where read performance matters more than write performance.
- Operating Systems: Some early Linux kernel internals and memory-management structures used AVL trees (though many have since moved to Red-Black Trees for their better write performance β see comparison table below).
- File Systems: Some directory-indexing implementations.
- Networking: Certain router/firewall rule-lookup structures where fast, predictable lookups matter and updates are relatively infrequent.
- Compilers/Language Runtimes: Some symbol table or interval-tracking implementations favor AVLβs tighter balance guarantee.
- Any read-heavy system requiring guaranteed worst-case performance: real-time systems where an occasional O(n) BST lookup (from an unlucky insertion order) would be unacceptable.
9. Implementation (C++17)
#include <iostream>
#include <memory>
#include <algorithm>
class AVLTree {
private:
struct Node {
int data;
int height; // height of the subtree rooted here (leaf = 1, empty = 0)
std::unique_ptr<Node> left;
std::unique_ptr<Node> right;
Node(int val) : data(val), height(1), left(nullptr), right(nullptr) {}
};
std::unique_ptr<Node> root;
int heightOf(const Node* node) const { return node ? node->height : 0; }
int balanceFactor(const Node* node) const {
return node ? heightOf(node->left.get()) - heightOf(node->right.get()) : 0;
}
void updateHeight(Node* node) {
node->height = 1 + std::max(heightOf(node->left.get()), heightOf(node->right.get()));
}
// Right rotation β fixes Left-Left imbalance. See ASCII diagram in section 3.
std::unique_ptr<Node> rotateRight(std::unique_ptr<Node> y) {
std::unique_ptr<Node> x = std::move(y->left);
y->left = std::move(x->right); // B moves from x's right to y's left
updateHeight(y.get());
x->right = std::move(y); // y becomes x's right child
updateHeight(x.get());
return x; // x is the new subtree root
}
// Left rotation β fixes Right-Right imbalance. Mirror image of rotateRight.
std::unique_ptr<Node> rotateLeft(std::unique_ptr<Node> x) {
std::unique_ptr<Node> y = std::move(x->right);
x->right = std::move(y->left);
updateHeight(x.get());
y->left = std::move(x);
updateHeight(y.get());
return y;
}
// Rebalance a node after insert/delete, applying the correct rotation case.
std::unique_ptr<Node> rebalance(std::unique_ptr<Node> node) {
updateHeight(node.get());
int bf = balanceFactor(node.get());
if (bf > 1) { // left-heavy
if (balanceFactor(node->left.get()) < 0) {
// Left-Right case: rotate left child left first, THEN rotate node right.
node->left = rotateLeft(std::move(node->left));
}
return rotateRight(std::move(node)); // Left-Left case (or LR after the fix-up above)
}
if (bf < -1) { // right-heavy
if (balanceFactor(node->right.get()) > 0) {
// Right-Left case: rotate right child right first, THEN rotate node left.
node->right = rotateRight(std::move(node->right));
}
return rotateLeft(std::move(node)); // Right-Right case (or RL after the fix-up above)
}
return node; // already balanced, no rotation needed
}
std::unique_ptr<Node> insertHelper(std::unique_ptr<Node> node, int value) {
if (!node) return std::make_unique<Node>(value);
if (value < node->data) {
node->left = insertHelper(std::move(node->left), value);
} else if (value > node->data) {
node->right = insertHelper(std::move(node->right), value);
} else {
return node; // duplicate, ignore
}
return rebalance(std::move(node)); // rebalance on the way back UP the recursion
}
std::unique_ptr<Node> deleteHelper(std::unique_ptr<Node> node, int value) {
if (!node) return nullptr;
if (value < node->data) {
node->left = deleteHelper(std::move(node->left), value);
} else if (value > node->data) {
node->right = deleteHelper(std::move(node->right), value);
} else {
if (!node->left) return rebalance(std::move(node->right));
if (!node->right) return rebalance(std::move(node->left));
Node* successor = node->right.get();
while (successor->left) successor = successor->left.get();
node->data = successor->data;
node->right = deleteHelper(std::move(node->right), successor->data);
}
return rebalance(std::move(node)); // rebalance on the way back UP, just like insert
}
public:
AVLTree() : root(nullptr) {}
void insert(int value) { root = insertHelper(std::move(root), value); }
void remove(int value) { root = deleteHelper(std::move(root), value); }
int height() const { return heightOf(root.get()); }
void inOrderPrint() const {
std::vector<int> result;
std::function<void(const Node*)> visit = [&](const Node* n) {
if (!n) return;
visit(n->left.get());
result.push_back(n->data);
visit(n->right.get());
};
visit(root.get());
std::cout << "[ ";
for (int v : result) std::cout << v << " ";
std::cout << "]\n";
}
};
// Example usage
int main() {
AVLTree tree;
// Insert already-SORTED data β this would make a plain BST a degenerate linked list.
for (int v : {10, 20, 30, 40, 50, 60}) {
tree.insert(v);
}
tree.inOrderPrint(); // [ 10 20 30 40 50 60 ] β still sorted
std::cout << "Tree height: " << tree.height() << "\n";
// Height stays ~3 (log2(6)β2.6), NOT 6 β proof the AVL rebalancing worked.
tree.remove(30);
tree.inOrderPrint(); // [ 10 20 40 50 60 ]
std::cout << "Tree height after delete: " << tree.height() << "\n";
return 0;
}
10. Code Walkthrough
heightfield per node: Unlike a plain BST, every AVL node tracks its own subtree height, updated bottom-up after every structural change. This is the raw materialbalanceFactorneeds.rotateRight/rotateLeft: Each is O(1) β notice they only touch three pointers (y->left,x->right, and the callerβs reference) and recompute two heights. The order of operations matters:updateHeight(y)must happen beforex->right = std::move(y)reassigns yβs new parent, since at that point yβs children are already correctly set but xβs height hasnβt been recomputed yet.rebalance: This is the single function bothinsertHelperanddeleteHelpercall on their way back up the recursion. It checksbf > 1(left-heavy) orbf < -1(right-heavy), and for each, checks the childβs balance factor to distinguish the βsingle rotationβ cases (LL/RR) from the βdouble rotationβ cases (LR/RL) β this nested check is exactly the four-case logic from section 3, compressed into twoifblocks thanks to symmetry.insertHelper/deleteHelpercallingrebalanceon every return: This is the critical difference from the plain BST in Chapter 6 β every single level of the recursion, from the insertion/deletion point all the way up to the root, gets a height update and a balance check. This is why an AVL tree can never end up skewed: imbalance is caught and fixed immediately at the lowest point it appears, before it can propagate.- Deletionβs
rebalance(std::move(node->right))/rebalance(std::move(node->left))for the 0/1-child cases: Even these βsimpleβ cases need rebalancing because removing a node can still shift the height of what remains, potentially imbalancing an ancestor.
Common mistakes to watch for here:
- Forgetting to call
updateHeightafter a rotation (or calling it in the wrong order relative to reassigning pointers), leaving stale height values that corrupt future balance-factor checks. - Applying only a single rotation for whatβs actually an LR/RL (double rotation) case β this is the single most common AVL bug.
- Forgetting to rebalance on the way back up for every ancestor, not just the immediate parent of the insertion/deletion point.
11. Dry Run
Insert 10, 20, 30 (triggers a Right-Right case):
| Step | Tree after insert | Balance check |
|---|---|---|
| insert(10) | 10 | bf(10)=0, fine |
| insert(20) | 10 β right:20 | bf(10) = 0 - 1 = -1, fine (within [-1,1]) |
| insert(30) | 30 goes right of 20 β 10 β 20 β 30 (a right-skewed chain) | At node 10: bf = 0 - 2 = -2 β imbalanced! Right-heavy. Check child(20)βs bf: 0 - 1 = -1 (not >0) β pure Right-Right case β single left rotation at 10. |
Applying rotateLeft(10):
Before: After:
10 20
\ / \
20 10 30
\
30
New balanced tree: root 20, left child 10, right child 30. Height = 2 (was about to become 3 unbalanced, now stays a perfect 2). β
Now insert 25 (triggers a Right-Left case on this new tree):
20
/ \
10 30
/
25
At node 30: bf = height(left=25,h1) - height(right=0) = 1 - 0 = 1β¦ check node 20 (the actual ancestor going out of balance): left height=1(node 10), right height=2(subtree rooted at 30 which now has height 2 because of 25) β bf(20) = 1 - 2 = -1, still fine actually in this small example β but in general, this exact pattern (new node inserted into left child of a right child) is the textbook Right-Left trigger, requiring right-rotate at 30, then left-rotate at 20.
12. Interview Questions
Conceptual:
- Why does an AVL tree guarantee O(log n) height, and whatβs the mathematical bound?
- Explain all four rotation cases (LL, RR, LR, RL) and how to detect which applies.
- Compare AVL Tree vs Red-Black Tree β why might a database prefer one over the other?
- Why must rebalancing happen on the way back up the recursion, not just at the insertion point?
- Can a single insertion require more than one rotation sequence? Can a single deletion?
Coding:
- Implement AVL tree insertion with rotations.
- Implement AVL tree deletion with rebalancing.
- Given a sequence of insertions, determine the final tree height.
- Convert an unbalanced BST into a balanced AVL tree (or general balanced BST).
- Verify whether a given binary tree satisfies the AVL balance property.
Follow-ups / interviewer traps:
- βWhatβs the worst-case number of rotations for one deletion?β (still O(log n) total, but can require rebalancing at every ancestor level β not just one rotation like insertion typically needs)
- βWhy not just rebuild the whole tree from scratch periodically instead of rotating incrementally?β (tests understanding of why O(1) local rotations beat O(n) global rebuilds)
- βIf you only rebalance the immediate parent instead of walking all the way to the root, what breaks?β (tests deep understanding β an ancestor further up could still be imbalanced)
13. Practice Problems
Easy
- Balanced Binary Tree β check if balanced (LeetCode 110)
- Convert Sorted Array to Binary Search Tree (LeetCode 108)
Medium
- Convert Sorted List to Binary Search Tree (LeetCode 109)
- Balance a Binary Search Tree (LeetCode 1382)
Hard
- Design a data structure supporting O(log n) insert/delete/search with order statistics (order-statistics tree, an AVL variant)
- Count of Smaller Numbers After Self (can be solved with a balanced BST / BIT)
Also recommended: GeeksforGeeks βAVL Treeβ practice set; implement your own AVL and stress-test it against a plain BST with sorted-input insertion to see the height difference firsthand β this is one of the most illuminating exercises in this whole guide.
14. Common Mistakes
- Implementing only single rotations, missing the double-rotation (LR/RL) cases entirely.
- Forgetting to update height after rotation, or updating it in the wrong order (before children are correctly reattached).
- Rebalancing only at the insertion/deletion point instead of at every ancestor on the path back to the root.
- Off-by-one in balance factor threshold β using
> 1when the tree actually needs checking at>= 2equivalent logic (these should be equivalent, but sign/direction errors are common). - Confusing which childβs balance factor to check when distinguishing LL/LR or RR/RL cases.
- Assuming AVL and Red-Black Trees are interchangeable in all contexts β they have the same asymptotic complexity but different practical performance profiles (see comparison table in the roadmap file).
15. Summary
Key takeaways:
- AVL trees fix the plain BSTβs single biggest weakness β no balance guarantee β by enforcing balance factor β {-1, 0, +1} at every node via rotations.
- There are exactly four imbalance cases (LL, RR, LR, RL), and the double-rotation cases (LR, RL) are the most commonly mishandled in practice.
- Rebalancing must occur at every ancestor on the path back to the root after insert/delete β this is what guarantees no skew can ever accumulate undetected.
- AVL trees favor read-heavy workloads (tighter balance β faster lookups); Red-Black Trees favor write-heavy workloads (looser balance β fewer rotations).
Complexity recap:
| Operation | Time (guaranteed) | Space |
|---|---|---|
| Search / Insert / Delete | O(log n) | O(log n) recursion stack |
| Single rotation | O(1) | O(1) |
Decision guideline: Choose an AVL Tree when you need guaranteed O(log n) performance and your workload is read-heavy (lookups >> insertions/deletions). Choose a Red-Black Tree (or just use std::map) when writes are frequent and you can tolerate slightly looser balance for fewer rotations. Choose a plain BST only when you can guarantee reasonably random insertion order and simplicity matters more than worst-case guarantees.
Next chapter: 08_trie.md, or say the word for Heap-based priority structures revisited, Graphs, or Advanced structures (Segment Tree, Fenwick Tree, DSU) instead.
Chapter 8: Trie (Prefix Tree)
Study time: ~5-6 hours | Prerequisite: Trees, Hash Tables | Difficulty: Intermediate
1. Introduction
Definition: A Trie (pronounced βtry,β from retrieval) is a tree-like structure specialized for storing strings, where each path from the root spells out a prefix, and each node represents one character. Nodes shared by multiple words merge into the same path.
Purpose: To support extremely fast prefix-based operations β βdoes any word start with βpreβ?β, βgive me all words starting with βcaββ β which a hash table cannot do efficiently.
Real-world analogy: A trie is like a dictionary organized as a decision tree of letters: to find βcat,β you go down C β A β T, and along the way, anyone looking for βcarβ shares the same C β A path with you before splitting off. Itβs the physical structure of an old-fashioned phone directoryβs alphabetical tabs, nested recursively.
Motivation: A hash set of strings answers βis this exact string present?β in O(1), but answering βwhat strings start with this prefix?β requires scanning every stored string β O(n Γ L). A trie answers both in time proportional only to the length of the query, independent of how many words are stored.
History: Introduced by Edward Fredkin in 1960, originally for information retrieval systems; now foundational to autocomplete, spell-checkers, and IP routing.
2. Why Do We Need It?
Problem it solves: Efficient prefix search, autocomplete, and spell-checking β operations built around βsequences that share a common start.β
Why previous structures are insufficient:
- Hash Set: O(1) exact match, but prefix search requires checking every stored string β O(nΒ·L).
- BST of strings: O(log n) exact match (with string comparison cost), but prefix search still requires an in-order-range scan and per-comparison string cost, not proportional purely to prefix length.
- Sorted array of strings: binary search finds an exact match or insertion point in O(log n Β· L), but enumerating βall words with prefix Xβ still means scanning a contiguous range, and that range could be O(n) in the worst case.
Trade-offs:
- You gain O(L) search/insert/prefix-lookup, where L is the stringβs length β independent of how many total words are stored.
- You pay for it with significant memory overhead β every node can have up to 26 (or more, per alphabet size) child pointers, most of which are unused, and shared prefixes are the only thing keeping memory from exploding.
3. Internal Working
Inserting the words βcatβ, βcarβ, βcardβ, βdogβ:
(root)
/ \
c d
| |
a o
/ \ |
t r g*
* |
d
*
(* marks a node where a complete word ends β the βend-of-wordβ flag, essential to distinguish βcarβ being a complete word from just being a prefix of βcardβ.)
Node structure:
struct TrieNode {
TrieNode* children[26]; // or a hash map for sparse alphabets / Unicode
bool isEndOfWord;
};
Insert βcarβ, step by step:
Start at root.
'c': root has no child 'c' yet β create it. Move to node 'c'.
'a': node 'c' has no child 'a' yet β create it. Move to node 'a'.
'r': node 'a' has no child 'r' yet β create it. Move to node 'r'.
Mark node 'r' as isEndOfWord = true.
Insert βcardβ afterward β reuses the existing cβaβr path entirely, only adding one new node:
'c': exists, reuse. 'a': exists, reuse. 'r': exists, reuse (already end-of-word for "car", stays true).
'd': node 'r' has no child 'd' yet β create it. Mark it as isEndOfWord = true.
This reuse of shared prefixes is the defining efficiency trick of a trie β words sharing a prefix share the memory for that prefixβs path.
Prefix search for βcaβ: walk c β a (2 steps, matching query length exactly), then all words below this point (βcatβ, βcarβ, βcardβ) can be found via a subtree traversal (DFS) from here.
4. Operations
Insert(word):
- Start at root. For each character, check if a child for that character exists; if not, create it. Move into that child.
- After processing all characters, mark the final nodeβs
isEndOfWord = true. - O(L) where L is the wordβs length.
Search(word) β exact match:
- Walk the trie character by character, following existing children.
- If any characterβs child doesnβt exist, the word isnβt present β return false.
- If all characters are matched, return
isEndOfWordat the final node (this distinguishes βcarβ being a full word vs. just a prefix of βcardβ).
StartsWith(prefix):
- Identical walk to Search, but simply return true if you successfully walk the entire prefix β you donβt check
isEndOfWord(a prefix need not be a complete word itself).
Delete(word):
- Walk down to the wordβs last node. If it has children, just unset
isEndOfWord(canβt delete nodes β theyβre needed for longer words sharing this prefix). - If it has no children, itβs safe to delete backward up the chain until hitting a node that either is
isEndOfWordfor another word or has other children. - Edge case: deleting a word thatβs a prefix of another stored word must never delete shared nodes.
Traverse (enumerate all words / autocomplete):
- DFS from a given node (e.g., after walking a prefix), collecting the accumulated character path whenever
isEndOfWordis true.
5. Time & Space Complexity
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Insert | O(L) | O(L) worst case (new path), O(1) if fully shared |
| Search (exact) | O(L) | O(1) |
| StartsWith (prefix check) | O(L) | O(1) |
| Enumerate all words with prefix | O(L + number of matching words Γ avg length) | O(1) extra beyond output |
| Overall storage | β | O(total characters across all words), bounded by O(ALPHABET_SIZE Γ total nodes) |
Why these hold:
- Every operationβs cost depends only on the length of the word/prefix being processed (L), not on how many words are stored overall (n) β this is the trieβs headline advantage over a hash set or BST, whose costs typically involve some function of n.
- Space is where the trade-off lives: in the worst case (no shared prefixes at all), a trie can use more memory than simply storing all strings directly, because every node reserves space for up to
ALPHABET_SIZEchildren (often 26 pointers) even if only one or two are used. Heavily-shared-prefix datasets (like a dictionary) benefit enormously; a set of totally random strings benefits much less.
6. Advantages
- O(L) search/insert, independent of the total number of stored words β scales beautifully as your dataset grows.
- Naturally supports prefix operations (autocomplete, βdoes any word start with Xβ) that hash tables cannot do efficiently.
- Shared prefixes reduce redundant storage compared to storing every string independently.
- Enumerating all words with a given prefix is straightforward (a simple DFS from the prefixβs end node).
7. Disadvantages
- High memory overhead per node when the alphabet is large or children are sparse (many unused pointers) β mitigated by using a hash map instead of a fixed-size array for children, at the cost of slightly higher constant-factor time.
- Not useful for non-string / non-sequence data.
- Cache-unfriendly (like any pointer-heavy tree) β many small allocations scattered in memory.
- Case sensitivity, Unicode, and special characters all need careful design decisions (e.g., mapping to a wider child array or a hash map).
8. Real-World Applications
- Search Engines / Autocomplete: Suggesting query completions as you type β exactly the βenumerate all words with this prefixβ operation.
- Spell Checkers: Quickly verifying whether a word exists, and suggesting nearby valid words (via limited edit-distance search over the trie).
- Networking: IP routing tables use a specialized trie (a βradix trieβ / βPatricia trieβ) to perform longest-prefix-matching for routing decisions β extremely performance-critical in real routers.
- Compilers: Some tokenizers/lexers use tries to efficiently match reserved keywords.
- AI/ML/NLP: Tokenization and vocabulary lookups in some NLP pipelines; representing large dictionaries compactly.
- Text Editors/IDEs: Code autocompletion (suggesting function/variable names as you type).
- Contact Lists/Phone Directories: Efficient prefix-based contact search.
9. Implementation (C++17)
#include <iostream>
#include <string>
#include <vector>
#include <memory>
class Trie {
private:
struct TrieNode {
// Using a fixed array for lowercase a-z. For wider alphabets/Unicode,
// swap this for std::unordered_map<char, std::unique_ptr<TrieNode>>.
std::unique_ptr<TrieNode> children[26];
bool isEndOfWord = false;
};
std::unique_ptr<TrieNode> root;
int charIndex(char c) const { return c - 'a'; }
// Recursive helper for enumerating all words at/below a given node.
void collectWords(TrieNode* node, std::string& prefix, std::vector<std::string>& results) const {
if (!node) return;
if (node->isEndOfWord) results.push_back(prefix);
for (int i = 0; i < 26; ++i) {
if (node->children[i]) {
prefix.push_back(static_cast<char>('a' + i));
collectWords(node->children[i].get(), prefix, results);
prefix.pop_back(); // backtrack β undo before trying the next branch
}
}
}
public:
Trie() : root(std::make_unique<TrieNode>()) {}
// Insert a word. O(L).
void insert(const std::string& word) {
TrieNode* current = root.get();
for (char c : word) {
int idx = charIndex(c);
if (!current->children[idx]) {
current->children[idx] = std::make_unique<TrieNode>();
}
current = current->children[idx].get();
}
current->isEndOfWord = true;
}
// Exact word search. O(L).
bool search(const std::string& word) const {
TrieNode* current = root.get();
for (char c : word) {
int idx = charIndex(c);
if (!current->children[idx]) return false;
current = current->children[idx].get();
}
return current->isEndOfWord; // must be a COMPLETE word, not just a prefix
}
// Prefix check. O(L). Does NOT require isEndOfWord.
bool startsWith(const std::string& prefix) const {
TrieNode* current = root.get();
for (char c : prefix) {
int idx = charIndex(c);
if (!current->children[idx]) return false;
current = current->children[idx].get();
}
return true;
}
// Autocomplete: return all stored words that begin with the given prefix.
std::vector<std::string> autocomplete(const std::string& prefix) const {
std::vector<std::string> results;
TrieNode* current = root.get();
for (char c : prefix) {
int idx = charIndex(c);
if (!current->children[idx]) return results; // no words with this prefix
current = current->children[idx].get();
}
std::string mutablePrefix = prefix;
collectWords(current, mutablePrefix, results);
return results;
}
};
// Example usage
int main() {
Trie trie;
for (const std::string& w : {"cat", "car", "card", "care", "dog"}) {
trie.insert(w);
}
std::cout << "search('car'): " << trie.search("car") << "\n"; // 1 (true)
std::cout << "search('ca'): " << trie.search("ca") << "\n"; // 0 (false β 'ca' is a prefix, not a complete word)
std::cout << "startsWith('ca'): " << trie.startsWith("ca") << "\n"; // 1 (true)
std::cout << "Autocomplete 'car': ";
for (const auto& word : trie.autocomplete("car")) std::cout << word << " ";
std::cout << "\n"; // car card care
return 0;
}
10. Code Walkthrough
children[26]array ofunique_ptr<TrieNode>: Each slot corresponds to one letter;nullptrmeans βno word passes through this character at this position.β Using smart pointers means deleting the whole trie (or any subtree) is automatic and leak-free.charIndex: Maps'a'β'z'to array indices0β25via simple subtraction β this is the entire βhashingβ a trie needs, since the alphabet is small and dense (contrast this with the Hash Table chapter, where keys are arbitrary and need an actual hash function).isEndOfWord: This flag is essential β without it, thereβd be no way to distinguish βcarβ being a complete stored word from merely being a prefix that happens to lead to βcard.β Notesearch("ca")returns false in the example even though the path exists, precisely because that nodeβs flag is false.collectWords(DFS with backtracking): Builds upprefixas it descends, appends a word toresultswhenever it passes anisEndOfWordnode, then explicitlypop_back()s before returning from each recursive call β this backtracking step is what lets the same mutable string buffer be reused across all 26 possible branches without needing to copy it at every level.autocomplete: First walks the prefix to find its ending node (O(L)), then hands off tocollectWordsto gather every complete word reachable below that point β this two-phase structure (walk then collect) is the standard trie autocomplete pattern.
Common mistakes to watch for here:
- Forgetting the
isEndOfWordcheck insearch, causing prefixes to be incorrectly reported as complete words. - Forgetting to
pop_back()after each recursive call incollectWords, causing the prefix string to accumulate incorrectly across sibling branches. - Using a fixed 26-size array for alphabets/character sets it doesnβt fit (uppercase, digits, Unicode) without adjusting
charIndexor switching to a hash-map-based children structure.
11. Dry Run
Insert βcatβ, βcarβ, βcardβ, then autocomplete("ca").
| Step | Trie state (paths from root) |
|---|---|
| insert(βcatβ) | rootβcβaβt* |
| insert(βcarβ) | rootβcβaβ(t*, r*) β βrβ is new, but c,a were reused |
| insert(βcardβ) | rootβcβaβrβd* β βdβ is new, c,a,r were reused (r stays end-of-word too) |
autocomplete("ca"):
- Walk βcβ β βaβ from root (2 steps) β both exist, arrive at node βaβ.
collectWordsfrom node βaβ, prefix=βcaβ:- node βaβ itself: not end-of-word (only βcaβ alone was never inserted) β skip adding.
- child βtβ: prefix becomes βcatβ β node βtβ is end-of-word β add βcatβ. Backtrack, prefix back to βcaβ.
- child βrβ: prefix becomes βcarβ β node βrβ is end-of-word β add βcarβ. Recurse further:
- child βdβ: prefix becomes βcardβ β node βdβ is end-of-word β add βcardβ. Backtrack.
- Backtrack fully back to βcaβ.
- Result:
["cat", "car", "card"](order depends on iteration order over children, here alphabetical since we loopi=0..25).
12. Interview Questions
Conceptual:
- Why is a trieβs time complexity independent of the number of stored words, unlike a hash set or BST?
- Why is
isEndOfWordnecessary β what breaks without it? - Compare a Trie vs a Hash Map for autocomplete β why does the hash map approach fail to scale for prefix queries?
- Whatβs the memory trade-off of using a fixed-size children array vs. a hash map for children?
- How would you extend a trie to support wildcard search (e.g., βc?tβ matching βcatβ, βcotβ)?
Coding:
- Implement Insert, Search, StartsWith (LeetCode 208 β Implement Trie).
- Word Search II β find all dictionary words present in a grid, using a trie to prune DFS branches.
- Design an Autocomplete System.
- Longest Word in Dictionary formed by concatenating other words.
- Replace Words β replace words in a sentence with their shortest root found in a trie (dictionary).
- Implement a trie supporting wildcard β.β matching in search.
Follow-ups / interviewer traps:
- βHow would you reduce memory usage for a trie storing millions of short words?β (expects discussion of compressed tries / radix tries, or switching to hash-map children for sparse branching)
- βCan you delete a word without breaking other stored words that share its prefix?β (tests understanding that shared nodes must never be deleted, only the
isEndOfWordflag or unshared suffix nodes) - βWhat if the same word is inserted twice β does your structure handle it correctly?β (tests idempotency of
isEndOfWordbeing set to true, not toggled)
13. Practice Problems
Easy
- Implement Trie (Prefix Tree) (LeetCode 208)
- Longest Common Prefix (LeetCode 14) β solvable with or without an explicit trie
Medium
- Design Add and Search Words Data Structure (LeetCode 211) β wildcard search
- Replace Words (LeetCode 648)
- Map Sum Pairs (LeetCode 677)
- Search Suggestions System (LeetCode 1268)
Hard
- Word Search II (LeetCode 212)
- Palindrome Pairs (LeetCode 336)
- Concatenated Words (LeetCode 472)
Also recommended: GeeksforGeeks βTrieβ practice set; try implementing autocomplete with ranked suggestions (most-frequently-searched-first) as an extension project.
14. Common Mistakes
- Forgetting the end-of-word marker, conflating βis a prefix of somethingβ with βis itself a complete stored word.β
- Not backtracking the prefix string during DFS-based word collection, corrupting later results.
- Assuming fixed-size children arrays work for all input β breaks immediately on uppercase, punctuation, digits, or Unicode without adjustment.
- Deleting shared nodes when removing a word that is a prefix of another stored word.
- Ignoring the memory cost of tries for datasets with little to no shared prefix structure β a hash set may be strictly better there.
- Off-by-one in
charIndex(e.g., forgetting that'a' - 'a' = 0, not 1).
15. Summary
Key takeaways:
- A trie trades memory for prefix-speed: every operation costs O(L) β the length of the word/prefix β regardless of how many total words are stored.
- The
isEndOfWordflag is the critical piece of bookkeeping that separates βprefixβ from βcomplete word.β - Shared prefixes are what make tries memory-efficient for prefix-heavy datasets (dictionaries, autocomplete corpora); for datasets without shared structure, the overhead can outweigh the benefit.
Complexity recap:
| Operation | Time | Space |
|---|---|---|
| Insert | O(L) | O(L) worst case |
| Search / StartsWith | O(L) | O(1) |
| Enumerate matches | O(L + matches) | O(1) extra |
Decision guideline: Choose a Trie when your workload centers on prefix operations β autocomplete, spell-check, longest-prefix matching. If you only need exact-match lookups with no prefix/autocomplete requirement, a Hash Set is simpler and often more memory-efficient.
Next chapter: 09_btree_overview.md
Chapter 9: B-Tree (Overview)
Study time: ~3-4 hours | Prerequisite: BST, AVL Tree | Difficulty: Intermediate (Marked βOverviewβ in the roadmap β this chapter emphasizes conceptual understanding over from-scratch implementation, since B-Trees are rarely hand-rolled outside database/filesystem internals.)
1. Introduction
Definition: A B-Tree is a self-balancing tree where each node can hold multiple keys (not just one, unlike a BST) and have multiple children (not just two). Keys within a node are kept sorted, and all leaves sit at the same depth.
Purpose: To minimize the number of disk reads needed to find data, by packing many keys into each node so the tree stays extremely short (shallow) even for enormous datasets.
Real-world analogy: A B-Tree node is like a single page in a massive multi-volume encyclopedia index β instead of one entry per page (like a BST node holding one key), each page lists dozens of entries with pointers to which volume/page to check next. You flip far fewer pages to find anything.
Motivation: An AVL or Red-Black Tree is optimized assuming memory access is roughly uniform in cost (RAM). But disk access is dramatically slower than RAM access β and each disk read typically pulls a whole fixed-size block regardless of how much you actually need. A B-Tree node is designed to exactly fill one disk block, so each disk read retrieves the maximum useful number of keys, minimizing the total number of (slow) disk reads for a search.
History: Introduced by Rudolf Bayer and Ed McCreight in 1972 at Boeing Research Labs, specifically to optimize large database and filesystem index structures.
2. Why Do We Need It?
Problem it solves: Efficient search/insert/delete on datasets too large to fit in memory, where the dominant cost is the number of disk block reads, not raw comparison count.
Why AVL/Red-Black Trees are insufficient here: A binary tree with n keys has height β logβ(n) β for a billion keys, thatβs ~30 levels, meaning up to 30 separate disk reads (each disk read can be milliseconds β extremely slow compared to RAM). A B-Tree with, say, 100 keys per node has height β logβββ(n) β for the same billion keys, only ~5 levels, meaning as few as 5 disk reads.
Trade-offs:
- You gain drastically fewer disk reads for large, disk-resident datasets β the actual bottleneck in real database/filesystem performance.
- You pay for it with more complex node-splitting/merging logic, and more wasted comparisons within a node (though these happen in fast RAM/cache, not on slow disk, so theyβre relatively cheap).
3. Internal Working
A B-Tree of order (max children) 4 β meaning each node holds up to 3 keys and 4 children:
[ 30 | 60 ]
/ | \
[10|20] [40|50] [70|80|90]
Searching for 45: compare against root keys (30, 60) β 45 is between 30 and 60 β follow the middle child pointer β land on [40|50] β compare β 45 is between 40 and 50 β but this is a leaf with no more children, and 45 isnβt among {40,50} β not found (in a real B-Tree, this leaf might actually contain 45 depending on order; the point is each node comparison narrows the search across multiple keys per step, not just one).
Node splitting (insertion overflow): When a node would exceed its maximum key count, it splits into two nodes, and its middle key moves up to the parent:
Before (node full with 5 keys, max allowed is 3, inserting a 6th triggers split):
[10|20|30|40|50] β overflow
Split into two nodes, middle key (30) promoted to parent:
[30]
/ \
[10|20] [40|50]
This splitting can cascade upward if the parent also overflows β in the worst case, all the way to the root, which is the only way a B-Treeβs height ever increases (uniformly across the whole tree, keeping it always perfectly balanced across all leaves).
Node merging (deletion underflow): When a node drops below its minimum key count after a deletion, it either borrows a key from a sibling (via the parent) or merges with a sibling β the mirror-image operation of splitting.
4. Operations
Search:
- Within a node, scan (or binary-search) its sorted keys to find the right child pointer to follow, or find the key itself.
- Recurse into the appropriate child until found or a leaf is exhausted without a match.
Insert:
- Find the correct leaf for the new key (same downward walk as search).
- Insert into the leafβs sorted key list.
- If the leaf now exceeds its maximum key count, split it and promote the middle key to the parent β this may cascade upward.
Delete:
- Find the key (possibly in an internal node, not just a leaf β B-Trees allow keys at any level).
- If deleting from an internal node, replace it with a predecessor/successor key from a leaf (similar in spirit to BST deletionβs in-order successor), then delete that leaf key.
- If a node drops below the minimum key count, borrow from a sibling or merge β this may cascade upward.
Traverse:
- In-order-style traversal (recursively visiting all children between consecutive keys) yields sorted output, just like a BST.
5. Time & Space Complexity
| Operation | Time Complexity | Notes |
|---|---|---|
| Search | O(log_m n) | m = max children per node (order); far fewer levels than a binary tree for large m |
| Insert | O(log_m n) | May trigger O(log_m n) splits cascading upward, each O(m) to redistribute keys |
| Delete | O(log_m n) | May trigger O(log_m n) merges/borrows cascading upward |
| Space | O(n) | Similar asymptotic space to any balanced tree; practical overhead is lower per key due to fewer pointers per key |
Why these hold:
- The height of a B-Tree with n keys and minimum degree (branching factor) m is O(log_m n) β and since m is typically large (tuned to match a disk block size, often in the hundreds), log_m n is dramatically smaller than logβ n for the same n. This is the entire point: fewer levels = fewer disk reads, even though the total asymptotic key-comparison work is similar.
- Within a single node, comparing against up to m-1 keys is technically O(m) (or O(log m) with binary search inside the node) β but since this happens in fast memory/cache after one disk read has already brought the whole node in, itβs essentially βfreeβ compared to the disk read itself.
6. Advantages
- Dramatically fewer disk/block reads for large, disk-resident datasets β the primary reason B-Trees dominate database and filesystem index design.
- Always perfectly height-balanced (every leaf at the same depth), unlike AVL (balanced within a factor) β height only changes uniformly via root splits.
- Efficient range queries (like a BST, in-order traversal gives sorted output) at scale.
7. Disadvantages
- More complex to implement than a BST/AVL β splitting/merging logic has several edge cases.
- Higher constant-factor overhead in RAM-only scenarios where disk I/O isnβt the bottleneck β an AVL/Red-Black tree can be simpler and just as fast when everything already fits in memory.
- Choosing the right βorderβ (branching factor) requires tuning to the underlying storage mediumβs block size for maximum benefit.
8. Real-World Applications
- Databases: Nearly every relational database (MySQLβs InnoDB, PostgreSQL, Oracle, SQL Server) uses B-Trees (or the closely related B+Tree) as its primary index structure.
- File Systems: NTFS, ext4, HFS+, and many modern filesystems use B-Trees (or B+Trees) to index files/directories for fast lookup.
- Key-Value Stores: Many embedded databases (e.g., LMDB, older versions of many storage engines) use B-Trees for on-disk storage layout.
- Operating Systems: Some kernel data structures indexing large on-disk metadata use B-Tree variants (e.g., Btrfs β literally named for B-Tree).
The unifying theme: any time the dataset lives primarily on disk (or any slow storage medium) rather than fully in RAM, a B-Tree (or B+Tree) is the default professional choice.
9. Implementation Note
Because B-Trees are almost never hand-implemented outside of database/filesystem internals (production code uses battle-tested library or kernel implementations), this βOverviewβ chapter intentionally skips a full from-scratch C++ implementation in favor of a clear conceptual walkthrough. If you want hands-on practice, the highest-value exercise is implementing insertion with node splitting for a small fixed order (e.g., order 4) β that single mechanic (split + promote middle key) is 80% of what makes a B-Tree tick, and is a common systems-interview whiteboard exercise. A skeleton to build from:
#include <vector>
#include <algorithm>
// Skeleton only β a full production B-Tree also needs deletion (borrow/merge),
// which is intentionally omitted here since it's rarely asked for in whiteboard form.
class BTreeNode {
public:
std::vector<int> keys;
std::vector<BTreeNode*> children; // children.size() == keys.size() + 1 when internal
bool isLeaf;
int maxKeys; // order - 1
BTreeNode(int maxKeys, bool leaf) : isLeaf(leaf), maxKeys(maxKeys) {}
// Insert into THIS node's key list assuming it's not yet full (caller's responsibility
// to have already split if needed before calling this).
void insertNonFull(int key) {
if (isLeaf) {
auto pos = std::upper_bound(keys.begin(), keys.end(), key);
keys.insert(pos, key);
} else {
// Find the child to descend into, splitting it first if it's already full.
size_t idx = std::upper_bound(keys.begin(), keys.end(), key) - keys.begin();
if (children[idx]->keys.size() == static_cast<size_t>(maxKeys)) {
splitChild(idx);
if (key > keys[idx]) idx++; // key may now belong to the newly split-off node
}
children[idx]->insertNonFull(key);
}
}
// Split a full child at index `idx`, promoting its middle key up into THIS node.
void splitChild(size_t idx) {
BTreeNode* fullChild = children[idx];
int mid = fullChild->keys.size() / 2;
int midKey = fullChild->keys[mid];
BTreeNode* newRight = new BTreeNode(maxKeys, fullChild->isLeaf);
newRight->keys.assign(fullChild->keys.begin() + mid + 1, fullChild->keys.end());
fullChild->keys.resize(mid); // left half keeps [0, mid)
if (!fullChild->isLeaf) {
newRight->children.assign(fullChild->children.begin() + mid + 1, fullChild->children.end());
fullChild->children.resize(mid + 1);
}
keys.insert(keys.begin() + idx, midKey); // promote middle key up
children.insert(children.begin() + idx + 1, newRight);
}
};
This shows the core mechanic β splitChild β without the full class wrapper (root management, search, deletion) that a production implementation would need.
10. Code Walkthrough (of the Skeleton)
insertNonFull: Assumes the node itβs called on is not already full β this precondition is whysplitChildis always called before recursing into a full child, never after. This βsplit-before-descendingβ strategy is what avoids ever having to propagate a split back up after the fact.splitChild: The middle key (midKey) is removed from the full child and promoted into the parentβs key list; the childβs remaining keys are divided into two halves, becoming two separate children. This is the exact mirror of the ASCII diagram in section 3.- Why split preemptively: By ensuring a node is never full before you insert into it (splitting proactively on the way down), the recursion never needs a second pass back up to handle overflow β a cleaner alternative to some textbook presentations that split after-the-fact.
11. Dry Run (Conceptual)
Given a B-Tree of order 4 (max 3 keys per node), inserting 10, 20, 30, 40, 50 in order:
| Insert | Result |
|---|---|
| 10, 20, 30 | Single node [10,20,30] β fits within max 3 keys |
| 40 | Node would become [10,20,30,40] β overflow! Split: middle key (30, using mid=len/2=2, keys[2]=30) promotes to a new root. Result: root [30], left child [10,20], right child [40] |
| 50 | 50 > 30, descend right to [40]. Insert: [40,50] β fits, no split needed |
Final structure: root [30], left [10,20], right [40,50] β tree height stayed at 2 despite 5 insertions, and would stay very shallow even for millions of keys with a realistically large order (e.g., order 100+).
12. Interview Questions
Conceptual:
- Why do databases use B-Trees instead of AVL/Red-Black Trees for disk-based indexes?
- Explain what happens when a B-Tree node overflows during insertion.
- Whatβs the difference between a B-Tree and a B+Tree? (B+Tree stores all actual data only in leaves, with internal nodes purely for navigation, and leaves are often linked for fast sequential range scans.)
- Why does a B-Treeβs height only ever grow uniformly (via root splits), unlike an unbalanced BST?
- How does the choice of βorderβ relate to the underlying disk block size?
Coding:
- Implement B-Tree insertion with node splitting (as in the skeleton above).
- Implement B-Tree search.
- (Advanced) Implement B-Tree deletion with borrow/merge.
Follow-ups / interviewer traps:
- βWhy not just use a hash table for a database index?β (tests understanding that B-Trees support range queries/sorted iteration, which hash indexes cannot)
- βWhatβs stored in the leaves of a B+Tree vs. a plain B-Tree?β (tests B+Tree vs B-Tree distinction β a very common systems-design follow-up)
13. Practice Problems
B-Trees are rarely LeetCode-style coding problems (theyβre more of a systems/database-design topic), but related concepts appear in:
- Design a simple in-memory database index (system design exercise).
- GeeksforGeeks βB-Treeβ practice/theory set for implementation practice.
- Study MySQL InnoDBβs or PostgreSQLβs actual B+Tree index documentation for real-world grounding.
14. Common Mistakes
- Confusing B-Tree with Binary Tree β the βBβ does not stand for βBinaryβ; a B-Tree node can have many more than 2 children.
- Splitting after overflow instead of before descending β leads to more complex βpropagate split back upβ logic; pre-emptive splitting (as in the skeleton) is simpler to reason about.
- Forgetting that internal nodes can store keys too (unlike a B+Tree, where only leaves hold actual data) β this affects how deletion of an internal key must borrow a replacement from a leaf.
- Choosing an arbitrarily small order in a real system β the whole point is tuning the order to match disk block size; a tiny order gives you all the complexity with none of the disk-read benefit.
15. Summary
Key takeaways:
- A B-Tree generalizes a BST to multiple keys and children per node, specifically to minimize the number of disk reads for huge, disk-resident datasets.
- Height is O(log_m n) where m is the branching factor β large m means very shallow trees even for billions of keys.
- Splitting (insertion) and merging/borrowing (deletion) keep the tree perfectly height-balanced at all times.
- This is the default index structure for virtually every production relational database and many filesystems.
Complexity recap:
| Operation | Time |
|---|---|
| Search / Insert / Delete | O(log_m n) |
Decision guideline: Reach for a B-Tree (or, in practice, use whatever your database/filesystem already provides) whenever your dataset is too large for RAM and minimizing disk/block reads is the dominant performance concern. For in-memory-only workloads, an AVL or Red-Black Tree is usually simpler and sufficiently fast.
Next chapter: 10_graphs_part1_representation_bfs_dfs.md
Chapter 10: Graphs β Part 1 (Representation, BFS, DFS)
Study time: ~6-8 hours | Prerequisite: Stack, Queue, Hash Table, Trees | Difficulty: Intermediate
1. Introduction
Definition: A graph is a collection of vertices (nodes) connected by edges. Unlike a tree, a graph allows cycles and doesnβt require a single root β any vertex can connect to any other, in any pattern.
Purpose: To model relationships and connections between entities β networks, dependencies, maps β where a strict hierarchy (tree) is too restrictive.
Real-world analogy: A tree is like a corporate org chart β one boss, strict hierarchy, no employee reports to two managers. A graph is like a social network β anyone can be βconnectedβ to anyone else, connections can form cycles (A knows B knows C knows A), and thereβs no single βroot person.β
Motivation: Countless real problems are naturally about connections rather than hierarchy: road networks, social networks, dependency graphs (build systems, course prerequisites), circuit diagrams. A tree literally cannot represent a cycle; a graph can represent everything a tree can (a tree is just a special, cycle-free, connected graph) and far more.
History: Graph theory traces to Eulerβs 1736 solution of the KΓΆnigsberg bridge problem β arguably the founding problem of the entire field, centuries before computers existed.
2. Why Do We Need It?
Problem it solves: Modeling and traversing arbitrary networks of relationships, including ones with cycles, multiple paths between points, and no natural βroot.β
Why trees are insufficient: A tree cannot represent a cycle (AβBβCβA) or a vertex with multiple βparentsβ (e.g., a file thatβs a dependency of two other files) without breaking its own definition. Graphs generalize away both restrictions.
Trade-offs:
- You gain the ability to model arbitrary connection patterns, including cycles and multiple paths.
- You pay for it with more complex traversal logic (must explicitly track βvisitedβ vertices to avoid infinite loops in cyclic graphs β trees never need this, since thereβs only ever one path down from the root).
3. Internal Working
Two standard representations:
(a) Adjacency Matrix β a 2D array where matrix[i][j] = 1 (or edge weight) if an edge exists from vertex i to vertex j:
Graph: 0 -- 1
| |
2 -- 3
0 1 2 3
0 [0, 1, 1, 0]
1 [1, 0, 0, 1]
2 [1, 0, 0, 1]
3 [0, 1, 1, 0]
(b) Adjacency List β each vertex stores a list of its directly connected neighbors (far more common in practice for sparse graphs):
0: [1, 2]
1: [0, 3]
2: [0, 3]
3: [1, 2]
Directed vs. Undirected: In an undirected graph, an edge (0,1) implies you can go both 0β1 and 1β0 (shown symmetrically above). In a directed graph, an edge only goes one way β adjacency list entries are not mirrored.
Directed: 0 β 1 β 2
Adjacency list:
0: [1]
1: [2]
2: [] (2 has no outgoing edges)
Weighted graphs store a cost alongside each edge (used heavily in shortest-path algorithms, covered in Part 2):
0: [(1, weight=4), (2, weight=1)]
4. Operations β Breadth-First Search (BFS)
BFS explores level by level β visit all neighbors of the start node first, then all neighbors-of-neighbors, and so on. It uses a Queue (FIFO) β this is the direct, essential link back to Chapter 3.
Why BFS finds shortest paths in unweighted graphs: because it exhausts every vertex at distance 1 before touching any vertex at distance 2, and so on β the first time it reaches a vertex is guaranteed to be via the shortest (fewest-edges) path.
Graph: 0
/ \
1 2
/ \
3 4
BFS from 0:
Step 1: visit 0. Queue: [1, 2]. Visited: {0}
Step 2: dequeue 1, visit. Queue: [2, 3]. Visited: {0,1}
Step 3: dequeue 2, visit. Queue: [3, 4]. Visited: {0,1,2}
Step 4: dequeue 3, visit. Queue: [4]. Visited: {0,1,2,3}
Step 5: dequeue 4, visit. Queue: []. Visited: {0,1,2,3,4}
Order visited: 0, 1, 2, 3, 4 β level by level
4b. Operations β Depth-First Search (DFS)
DFS explores as deep as possible down one branch before backtracking β it uses a Stack (LIFO), either explicitly or implicitly via recursion (the call stack itself is a stack β the direct link back to Chapter 3βs βwhy is it called a stackβ discussion).
Same graph, DFS from 0 (using recursion):
visit 0 β go to neighbor 1 β visit 1 β go to neighbor 3 β visit 3 (dead end, backtrack)
β back to 1 (no more neighbors, backtrack) β back to 0 β go to neighbor 2 β visit 2
β go to neighbor 4 β visit 4 (dead end, backtrack) β done
Order visited: 0, 1, 3, 2, 4 β deep before wide
Both BFS and DFS require a visited set (typically a hash set or boolean array) β without it, a cyclic graph would cause infinite traversal, re-visiting the same vertices forever.
5. Time & Space Complexity
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| BFS (full traversal) | O(V + E) | O(V) β queue + visited set |
| DFS (full traversal) | O(V + E) | O(V) β recursion stack / explicit stack + visited set |
| Adjacency Matrix space | O(VΒ²) | β |
| Adjacency List space | O(V + E) | β |
| Edge lookup (matrix) | O(1) | β |
| Edge lookup (list) | O(degree of vertex) | β |
Why these hold:
- BFS/DFS are O(V + E) because each vertex is visited exactly once (thanks to the
visitedset preventing re-visits β O(V) total), and each edge is examined exactly once (or twice for undirected, still a constant factor) while exploring neighbors β O(E) total. - Adjacency Matrix uses O(VΒ²) space regardless of how many edges actually exist β wasteful for sparse graphs (few edges relative to VΒ²) but O(1) edge-existence lookup makes it good for dense graphs or when βis there an edge between i and j?β is queried very frequently.
- Adjacency List uses O(V + E) space β proportional to whatβs actually there β making it the default choice for most real-world (typically sparse) graphs.
6. Advantages
Graphs in general:
- Model arbitrary relationships that trees cannot (cycles, multiple paths, no single root).
- A rich, well-studied algorithmic toolkit (BFS, DFS, and β Part 2 β shortest path, MST, topological sort) covers an enormous range of real problems.
BFS specifically: guarantees shortest path in unweighted graphs; naturally explores βclosest things firstβ (useful for level-based problems like βdegrees of separationβ).
DFS specifically: simpler to implement recursively; naturally suited to problems involving exhaustive exploration, backtracking, and structural analysis (cycle detection, connected components, topological sort β Part 2).
7. Disadvantages
- Both BFS and DFS require O(V) extra space for the visited set/queue/stack β can be significant for huge graphs.
- BFS can use more memory at any given moment than DFS for wide graphs (the queue can hold an entire βlevelβ of vertices at once).
- DFSβs recursive implementation risks stack overflow on very deep graphs (mitigated by converting to an explicit iterative stack-based version).
- Neither is βfasterβ than the other in Big-O terms (both O(V+E)) β the choice depends entirely on the problemβs requirements (shortest path β BFS; exhaustive/structural exploration β DFS), not raw speed.
8. Real-World Applications
- Social Networks: βDegrees of separationβ / βpeople you may knowβ features β BFS from a user finds friends-of-friends level by level.
- Networking: Network broadcast/routing protocols that need to reach all nodes with minimum hop count use BFS-like flooding.
- Web Crawlers: Crawling links breadth-first (or depth-first) to discover a websiteβs structure.
- Maze/Puzzle Solvers: BFS finds the shortest solution path; DFS explores all possible paths (useful when any valid solution, not necessarily shortest, is needed).
- Compilers: DFS is used to detect cycles in dependency graphs (e.g., circular imports) and for topological sort (Part 2).
- Game Development: Pathfinding on grid-based maps (BFS for unweighted grids; more advanced algorithms like A* for weighted ones).
- Operating Systems: Deadlock detection (a cycle in a βwaits-forβ resource graph) uses DFS-based cycle detection.
9. Implementation (C++17)
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_set>
#include <stack>
// A simple undirected graph using an adjacency list.
class Graph {
private:
int numVertices;
std::vector<std::vector<int>> adjList;
public:
Graph(int n) : numVertices(n), adjList(n) {}
// Add an undirected edge. O(1).
void addEdge(int u, int v) {
adjList[u].push_back(v);
adjList[v].push_back(u); // undirected: add both directions
}
// Breadth-First Search from a start vertex. O(V + E).
std::vector<int> bfs(int start) {
std::vector<int> order;
std::vector<bool> visited(numVertices, false);
std::queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
int current = q.front();
q.pop();
order.push_back(current);
for (int neighbor : adjList[current]) {
if (!visited[neighbor]) {
visited[neighbor] = true; // mark visited when ENQUEUED, not when dequeued β
q.push(neighbor); // this avoids adding the same vertex twice to the queue
}
}
}
return order;
}
// Depth-First Search from a start vertex, RECURSIVE version. O(V + E).
void dfsRecursiveHelper(int current, std::vector<bool>& visited, std::vector<int>& order) {
visited[current] = true;
order.push_back(current);
for (int neighbor : adjList[current]) {
if (!visited[neighbor]) {
dfsRecursiveHelper(neighbor, visited, order);
}
}
}
std::vector<int> dfsRecursive(int start) {
std::vector<int> order;
std::vector<bool> visited(numVertices, false);
dfsRecursiveHelper(start, visited, order);
return order;
}
// Depth-First Search, ITERATIVE version using an explicit stack (avoids recursion-depth limits).
std::vector<int> dfsIterative(int start) {
std::vector<int> order;
std::vector<bool> visited(numVertices, false);
std::stack<int> s;
s.push(start);
while (!s.empty()) {
int current = s.top();
s.pop();
if (visited[current]) continue; // may be pushed multiple times before being visited
visited[current] = true;
order.push_back(current);
// Push neighbors in reverse to roughly match recursive DFS's visiting order.
for (auto it = adjList[current].rbegin(); it != adjList[current].rend(); ++it) {
if (!visited[*it]) s.push(*it);
}
}
return order;
}
};
// Example usage
int main() {
Graph g(5); // vertices 0..4
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 4);
std::cout << "BFS from 0: ";
for (int v : g.bfs(0)) std::cout << v << " ";
std::cout << "\n"; // 0 1 2 3 4
std::cout << "DFS (recursive) from 0: ";
for (int v : g.dfsRecursive(0)) std::cout << v << " ";
std::cout << "\n"; // 0 1 3 2 4
std::cout << "DFS (iterative) from 0: ";
for (int v : g.dfsIterative(0)) std::cout << v << " ";
std::cout << "\n"; // 0 1 3 2 4
return 0;
}
10. Code Walkthrough
adjListasvector<vector<int>>: The standard sparse-graph representation βadjList[u]holds every vertex directly reachable fromu.addEdgepushes to bothadjList[u]andadjList[v]for an undirected edge; a directed graph would push only one direction.bfsβs βmark visited when enqueued, not dequeuedβ: This is a subtle but important detail β if you waited until dequeuing to mark a vertex visited, the same vertex could be pushed onto the queue multiple times (once from each neighbor that discovers it) before itβs ever processed, wasting time and potentially corrupting the traversal order.dfsRecursiveHelper: The recursion itself acts as the βstackβ β each call frame holdscurrent, and returning from a call is exactly the βpop and backtrackβ step DFS needs. This is why DFS is so naturally expressed recursively, unlike BFS.dfsIterative: Explicitly manages astd::stack<int>instead of relying on the call stack β necessary for very deep graphs where recursion could overflow. Note theif (visited[current]) continue;check β because a vertex can be pushed multiple times (once per edge pointing to it) before being popped and processed, we must re-check visited status after popping, not just before pushing.- Order difference (BFS vs both DFS versions): Running the example shows BFS visiting
0,1,2,3,4(level by level) versus DFS visiting0,1,3,2,4(deep into the 1-branch before backtracking to explore 2) β a direct visual confirmation of the βlevel by levelβ vs. βdeep firstβ distinction from section 4.
Common mistakes to watch for here:
- Forgetting the
visitedarray/set entirely β causes infinite loops on any graph with a cycle. - Marking visited at the wrong time in BFS (on dequeue instead of enqueue), allowing duplicate queue entries.
- Assuming DFS order is unique/deterministic β it depends on the order neighbors are stored/iterated, which can vary.
11. Dry Run
Graph: 0-1, 0-2, 1-3, 2-4 (as in the code example). BFS from 0:
| Step | Dequeue | Visit order so far | Queue after processing |
|---|---|---|---|
| 1 | (start) 0 | [0] | enqueue 1,2 β [1,2] |
| 2 | 1 | [0,1] | enqueue 3 (2 already queued, 0 already visited) β [2,3] |
| 3 | 2 | [0,1,2] | enqueue 4 β [3,4] |
| 4 | 3 | [0,1,2,3] | no new neighbors β [4] |
| 5 | 4 | [0,1,2,3,4] | no new neighbors β [] |
DFS (recursive) from 0:
| Call | Action |
|---|---|
| dfs(0) | visit 0. Neighbors: 1, 2. Recurse into 1 first. |
| dfs(1) | visit 1. Neighbors: 0(visited), 3. Recurse into 3. |
| dfs(3) | visit 3. Neighbors: 1(visited). Dead end, return. |
| (back in dfs(1)) | no more neighbors, return. |
| (back in dfs(0)) | continue to neighbor 2. Recurse into 2. |
| dfs(2) | visit 2. Neighbors: 0(visited), 4. Recurse into 4. |
| dfs(4) | visit 4. Neighbors: 2(visited). Dead end, return. |
Final order: 0, 1, 3, 2, 4 β matches the code output. β
12. Interview Questions
Conceptual:
- Why does BFS guarantee the shortest path in an unweighted graph, but DFS does not?
- Compare adjacency matrix vs. adjacency list β when would you pick each?
- Why is a
visitedset essential for graph traversal but never needed for tree traversal? - Whatβs the space/time trade-off between recursive and iterative DFS?
- How would you detect a cycle in an undirected graph vs. a directed graph? (Different techniques β undirected uses simple visited-tracking with parent-skip; directed needs a third βcurrently in recursion stackβ state to distinguish a back-edge from a cross-edge.)
Coding:
- Number of Islands β count connected components in a grid using BFS or DFS.
- Detect a cycle in an undirected graph.
- Detect a cycle in a directed graph.
- Clone a graph (deep copy with cycles).
- Find all connected components in an undirected graph.
- Word Ladder β shortest transformation sequence (BFS on an implicit graph).
- Rotting Oranges β multi-source BFS.
Follow-ups / interviewer traps:
- βWhat if the graph is disconnected β does a single BFS/DFS call from one vertex cover everything?β (no β need to iterate over all unvisited vertices and re-run traversal from each)
- βCan you do BFS with multiple starting points simultaneously?β (yes β multi-source BFS, seed the queue with all sources before starting; used in Rotting Oranges-style problems)
- βYour recursive DFS β what happens on a graph with a million vertices in a single chain?β (tests awareness of stack overflow risk, expects the iterative version)
13. Practice Problems
Easy
- Find the Town Judge (LeetCode 997) β light graph modeling
- Flood Fill (LeetCode 733)
Medium
- Number of Islands (LeetCode 200)
- Clone Graph (LeetCode 133)
- Course Schedule (LeetCode 207) β previews topological sort, Part 2
- Rotting Oranges (LeetCode 994)
- Word Ladder (LeetCode 127)
Hard
- Word Ladder II (LeetCode 126)
- Bus Routes (LeetCode 815)
- Minimum Height Trees (LeetCode 310)
Also recommended: GeeksforGeeks βGraph Data Structureβ practice set, Codeforces problems tagged graphs + dfs and similar (start around 1000-1300 rating).
14. Common Mistakes
- Forgetting the
visitedtracker, causing infinite loops on cyclic graphs. - Only traversing from one starting vertex when the graph might be disconnected, missing entire components.
- Marking visited at the wrong point in BFS (on dequeue vs. enqueue), causing duplicate processing.
- Confusing directed and undirected edge handling β forgetting to add both directions for undirected graphs, or accidentally adding both for a directed graph.
- Assuming DFS/BFS visiting order is unique β it depends on adjacency list ordering, which can differ between implementations even for the same graph.
- Recursion depth issues on deep/large graphs with recursive DFS β not considering the iterative alternative when it matters.
15. Summary
Key takeaways:
- Graphs generalize trees by allowing cycles and multiple paths β this power requires explicit cycle-avoidance (
visitedtracking) that trees never need. - BFS (Queue-based) explores level by level and guarantees shortest path in unweighted graphs.
- DFS (Stack/recursion-based) explores deep before wide β better suited to exhaustive/structural problems (cycle detection, connected components, topological sort).
- Adjacency List is the default representation for most real-world (sparse) graphs; Adjacency Matrix suits dense graphs or frequent O(1) edge-existence checks.
Complexity recap:
| Time | Space | |
|---|---|---|
| BFS | O(V + E) | O(V) |
| DFS | O(V + E) | O(V) |
Decision guideline: Use BFS when you need the shortest path in an unweighted graph or need to process things βclosest firstβ (level by level). Use DFS when you need exhaustive exploration, structural analysis (cycles, components), or when recursion naturally fits the problem (backtracking-style search).
Next chapter: 11_graphs_part2_topological_sort_mst_shortest_path.md β covers Topological Sort, Minimum Spanning Tree (Kruskal/Prim), and Shortest Path (Dijkstra/Bellman-Ford), which build directly on BFS/DFS plus the Heap and DSU structures.
Chapter 11: Topological Sort
Study time: ~4-5 hours | Prerequisite: Graphs (Representation, BFS, DFS) | Difficulty: Intermediate
1. Introduction
Definition: A topological sort is a linear ordering of the vertices of a Directed Acyclic Graph (DAG) such that for every directed edge u β v, vertex u appears before vertex v in the ordering. It only exists for graphs with no cycles β hence βacyclicβ being a hard requirement.
Purpose: To determine a valid processing order for tasks with dependencies β βdo this before that.β
Real-world analogy: Getting dressed. You must put on socks before shoes, and underwear before pants β some tasks have hard prerequisites. A topological sort is exactly βgive me a valid order to put my clothes onβ β there might be multiple valid orders (socks and underwear can be done in either order relative to each other), but shoes can never come before socks.
Motivation: Whenever tasks have dependency constraints (course prerequisites, build systems compiling files in the right order, spreadsheet formula evaluation order, package manager install order), you need an ordering that respects every βmust come beforeβ rule simultaneously β checking this by hand becomes infeasible as the dependency graph grows.
History: Formalized as a standard graph algorithm in the early days of computer science, closely tied to DFS (via Kahnβs contemporaries) and to Kahnβs 1962 BFS-based algorithm (covered below) developed for job-scheduling problems.
2. Why Do We Need It?
Problem it solves: Producing a valid execution/processing order for a set of tasks with directed βmust precedeβ dependencies, or detecting that no valid order exists (i.e., a cycle β a genuine circular dependency, like βA depends on B depends on A,β which is unsatisfiable).
Why plain BFS/DFS arenβt enough on their own: BFS/DFS traverse a graph, but a traversal order isnβt automatically a valid dependency order β you need extra bookkeeping (either counting incoming edges, or tracking finish times) specifically designed to respect the βbeforeβ relationship.
Trade-offs:
- You gain a provably valid processing order (or a clear signal that no valid order exists, due to a cycle).
- The cost is modest β topological sort is still O(V + E), just BFS/DFS with a bit of extra bookkeeping β thereβs no significant trade-off here beyond the requirement that the graph must be acyclic and directed.
3. Internal Working
Two standard algorithms β both O(V+E):
(a) Kahnβs Algorithm (BFS-based):
- Compute the in-degree (number of incoming edges) of every vertex.
- Start with all vertices that have in-degree 0 (no prerequisites) in a queue.
- Repeatedly dequeue a vertex, add it to the result, and decrement the in-degree of all its neighbors. Any neighbor whose in-degree drops to 0 gets enqueued.
- If the result includes all vertices, itβs a valid topological order. If not (some vertices never reach in-degree 0), the graph has a cycle.
Graph: A β B β D
A β C β D
In-degrees: A=0, B=1, C=1, D=2
Step 1: queue = [A] (only in-degree-0 vertex)
Step 2: dequeue A, add to result [A]. Decrement B(β0), C(β0). Queue = [B, C]
Step 3: dequeue B, add to result [A,B]. Decrement D(β1). D not 0 yet. Queue = [C]
Step 4: dequeue C, add to result [A,B,C]. Decrement D(β0). Queue = [D]
Step 5: dequeue D, add to result [A,B,C,D]. Queue = []
Result: A, B, C, D β a valid order (B/C order could also swap; both are valid).
(b) DFS-based Algorithm:
- Run DFS from every unvisited vertex.
- When a vertex finishes exploring all its descendants (i.e., DFS is about to return/backtrack from it), push it onto a stack.
- After all DFS calls finish, pop the stack β that pop order is the topological order.
Why this works: if u β v, DFS starting at u will fully explore v (and everything reachable from v) before u finishes and gets pushed β so v always gets pushed (and therefore popped) in a position consistent with coming afterβ¦ wait, more precisely: v finishes before u (since u waits for vβs subtree to complete), so v is pushed first, meaning u ends up above v on the stack, and therefore popped before v β giving u before v in the final order, exactly satisfying the requirement.
Same graph, DFS from A:
DFS(A) β DFS(B) β DFS(D) [no unvisited neighbors, push D] β back to B [push B]
β DFS(C) [D already visited] [push C]
β back to A [push A]
Stack (bottom to top): D, B, C, A
Pop order: A, C, B, D β a valid topological order (A first, D last)
4. Operations
Build the graph: Standard adjacency list, but must be directed (edges represent one-way βmust precedeβ relationships).
Compute topological order (Kahnβs):
- Compute in-degrees for all vertices β O(V + E).
- Initialize queue with all in-degree-0 vertices.
- Process the queue: dequeue, output, decrement neighborsβ in-degrees, enqueue any that reach 0.
- Edge case: if the final output size < total vertex count, a cycle exists β no valid topological order.
Compute topological order (DFS-based):
- Track visited vertices.
- For each unvisited vertex, run DFS; on finishing a vertex (all its neighbors processed), push it to a result stack.
- After all vertices are processed, reverse the stack (or pop it) for the final order.
- Edge case: detecting a cycle requires an additional βcurrently in recursion stackβ marker per vertex (distinct from plain βvisitedβ) β if DFS revisits a vertex thatβs still in its own current recursion path, thatβs a back-edge, confirming a cycle.
Cycle detection: A natural byproduct of both algorithms β Kahnβs signals a cycle if not all vertices get processed; DFS signals a cycle if it ever encounters a vertex still βin progressβ on the current path.
5. Time & Space Complexity
| Algorithm | Time Complexity | Space Complexity |
|---|---|---|
| Kahnβs (BFS-based) | O(V + E) | O(V) for in-degree array + queue |
| DFS-based | O(V + E) | O(V) for visited tracking + recursion stack + result stack |
Why these hold: Both algorithms are fundamentally BFS or DFS with O(1) extra bookkeeping per vertex/edge (tracking in-degree or push/pop timing) β so the complexity remains exactly the same as plain graph traversal: every vertex processed once (O(V)), every edge examined once (O(E)).
6. Advantages
- Provides a valid, deterministic-enough (up to tie ordering) processing order for dependency-based problems.
- Naturally detects cycles (unsatisfiable dependency sets) as a side effect β extremely useful for validating input before attempting to process it.
- Both algorithms are simple extensions of BFS/DFS, so no new fundamental machinery is required once those are understood.
7. Disadvantages
- Only defined for Directed Acyclic Graphs β a single cycle anywhere makes the entire concept undefined (though detecting that cycle is itself valuable information).
- Multiple valid topological orders can exist for the same graph β if a specific order matters (not just any valid one), topological sort alone isnβt sufficient; youβd need additional tie-breaking criteria.
8. Real-World Applications
- Build Systems: Compilers/build tools (Make, Bazel, Webpack) determine the order to compile/bundle files based on their
#include/importdependency graph. - Package Managers: npm, pip, apt determine installation order so dependencies are installed before the packages that need them.
- Course Scheduling: University course registration systems determine a valid order to take courses given prerequisite chains.
- Spreadsheet Software: Excel/Google Sheets determine the order to recalculate cells based on formula dependencies (cell A2 depends on A1, so A1 must be computed first).
- Task Scheduling / CI/CD Pipelines: Determining the order to run build/test/deploy stages that depend on each other.
- Compilers: Instruction scheduling and dependency resolution in some compiler optimization passes.
9. Implementation (C++17)
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
class DirectedGraph {
private:
int numVertices;
std::vector<std::vector<int>> adjList;
public:
DirectedGraph(int n) : numVertices(n), adjList(n) {}
// Directed edge: u must come before v.
void addEdge(int u, int v) {
adjList[u].push_back(v);
}
// Kahn's Algorithm (BFS-based). O(V + E).
// Returns empty vector if a cycle exists (no valid topological order).
std::vector<int> topoSortKahn() {
std::vector<int> inDegree(numVertices, 0);
for (int u = 0; u < numVertices; ++u) {
for (int v : adjList[u]) {
inDegree[v]++;
}
}
std::queue<int> q;
for (int v = 0; v < numVertices; ++v) {
if (inDegree[v] == 0) q.push(v); // no prerequisites β can go first
}
std::vector<int> result;
while (!q.empty()) {
int u = q.front();
q.pop();
result.push_back(u);
for (int v : adjList[u]) {
inDegree[v]--; // u is "done," remove its influence on v
if (inDegree[v] == 0) {
q.push(v); // v's prerequisites are now all satisfied
}
}
}
if (static_cast<int>(result.size()) != numVertices) {
return {}; // cycle detected β not all vertices could be processed
}
return result;
}
// DFS-based topological sort. O(V + E). Also detects cycles via a "in-progress" marker.
bool dfsTopoHelper(int u, std::vector<int>& state, std::stack<int>& finishOrder) {
// state: 0 = unvisited, 1 = in progress (on current DFS path), 2 = fully finished
state[u] = 1;
for (int v : adjList[u]) {
if (state[v] == 1) return false; // back-edge to an in-progress vertex β CYCLE
if (state[v] == 0 && !dfsTopoHelper(v, state, finishOrder)) {
return false; // cycle detected deeper in the recursion
}
}
state[u] = 2;
finishOrder.push(u); // push AFTER all descendants are fully processed
return true;
}
std::vector<int> topoSortDFS() {
std::vector<int> state(numVertices, 0);
std::stack<int> finishOrder;
for (int v = 0; v < numVertices; ++v) {
if (state[v] == 0) {
if (!dfsTopoHelper(v, state, finishOrder)) {
return {}; // cycle detected
}
}
}
std::vector<int> result;
while (!finishOrder.empty()) {
result.push_back(finishOrder.top());
finishOrder.pop();
}
return result;
}
};
// Example usage
int main() {
DirectedGraph g(4); // vertices: 0=A, 1=B, 2=C, 3=D
g.addEdge(0, 1); // A -> B
g.addEdge(0, 2); // A -> C
g.addEdge(1, 3); // B -> D
g.addEdge(2, 3); // C -> D
std::cout << "Kahn's topo order: ";
for (int v : g.topoSortKahn()) std::cout << v << " ";
std::cout << "\n"; // 0 1 2 3 (A B C D)
std::cout << "DFS-based topo order: ";
for (int v : g.topoSortDFS()) std::cout << v << " ";
std::cout << "\n"; // 0 2 1 3 (a different but equally valid order)
// Introduce a cycle: D -> A
DirectedGraph gCycle(4);
gCycle.addEdge(0, 1);
gCycle.addEdge(1, 2);
gCycle.addEdge(2, 3);
gCycle.addEdge(3, 0); // creates a cycle: 0->1->2->3->0
auto result = gCycle.topoSortKahn();
std::cout << "Cyclic graph result size: " << result.size() << " (0 means cycle detected)\n";
return 0;
}
10. Code Walkthrough
inDegreecomputation: A single pass over every edge increments the destination vertexβs in-degree β this is the βhow many prerequisites does each vertex haveβ count that Kahnβs algorithm is built around.- Kahnβs queue seeding: Only vertices with
inDegree == 0start in the queue β these are tasks with no unmet prerequisites, i.e., valid starting points. - Kahnβs main loop: Each time a vertex
uis processed, we decrement in-degree for all its neighbors (simulating βuβs prerequisite is now satisfied for vβ) β and any neighbor reaching exactly 0 becomes newly eligible. result.size() != numVerticescheck: If a cycle exists, at least one vertexβs in-degree will never reach 0 (since its prerequisite chain loops back on itself), so it never enters the queue β meaning the finalresultis smaller than the total vertex count. This is the cycle-detection mechanism, entirely for free from the algorithmβs natural behavior.- DFSβs three-state tracking (
0/1/2): This is the key upgrade over plain DFSβs simple visited/unvisited boolean. State1(βin progress,β i.e., currently on the active recursion path) is what lets us distinguish a genuine cycle (an edge back to a vertex still1) from simply revisiting an already-fully-processed vertex (state2, perfectly normal in a DAG with multiple paths converging on the same vertex, like both B and C leading to D above). - Pushing onto
finishOrderonly after theforloop completes: This ensures a vertex is only marked βfinishedβ once every single one of its dependents (things it points to) has also finished β guaranteeing the pop order respects all βbeforeβ constraints.
Common mistakes to watch for here:
- Using a simple 2-state (visited/unvisited) check for DFS cycle detection instead of 3-state β this incorrectly flags convergent (non-cyclic) paths as cycles.
- Forgetting to reverse/pop-order the DFS finish stack β pushing order and topological order are exact opposites.
- Not handling disconnected components β must loop over all vertices as potential DFS starting points, not just vertex 0.
11. Dry Run
Graph: AβB, AβC, BβD, CβD (0=A,1=B,2=C,3=D). Kahnβs Algorithm:
| Step | inDegree[0..3] | Queue | Result |
|---|---|---|---|
| init | [0,1,1,2] | [0] | [] |
| process 0 | [0,0,0,2] | [1,2] | [0] |
| process 1 | [0,0,0,1] | [2] | [0,1] |
| process 2 | [0,0,0,0] | [3] | [0,1,2] |
| process 3 | [0,0,0,0] | [] | [0,1,2,3] |
Result: [A, B, C, D] β valid (both B and C only need A, so either could technically go first; this particular run happened to process B before C due to insertion order).
12. Interview Questions
Conceptual:
- Why must a topological sort only exist for a Directed Acyclic Graph?
- Compare Kahnβs algorithm and the DFS-based approach β when might you prefer one over the other?
- How does each algorithm detect a cycle, and what does that detection mean practically (e.g., for a build system)?
- Can a graph have more than one valid topological order? Give an example of when it would have exactly one.
- How would you find the lexicographically smallest topological order among all valid ones? (Hint: use a min-heap instead of a plain queue in Kahnβs algorithm.)
Coding:
- Course Schedule β determine if all courses can be finished given prerequisites (cycle detection).
- Course Schedule II β return a valid course order.
- Alien Dictionary β derive character ordering from a list of words (build a graph from adjacent-letter constraints, then topological sort).
- Minimum Height Trees β related tree-centroid problem using topological-sort-like peeling of leaves.
- Sequence Reconstruction β determine if a given sequence is the unique topological order of a graph.
Follow-ups / interviewer traps:
- βWhat if there are multiple valid orders β how would you find the lexicographically smallest?β (expects swapping the queue for a min-heap, giving O(E log V) instead of O(E))
- βYour graph has a self-loop (u β u) β does your cycle detection catch it?β (tests edge-case robustness β a self-loop is a cycle of length 1)
- βHow would you parallelize task execution given a topological order?β (tests understanding that all in-degree-0 vertices at any given βwaveβ of Kahnβs algorithm can run concurrently)
13. Practice Problems
Easy
- Minimum Number of Vertices to Reach All Nodes (LeetCode 1557)
Medium
- Course Schedule (LeetCode 207)
- Course Schedule II (LeetCode 210)
- Sequence Reconstruction (LeetCode 444)
- Sort Items by Groups Respecting Dependencies (LeetCode 1203)
Hard
- Alien Dictionary (LeetCode 269)
- Parallel Courses III (LeetCode 2050)
Also recommended: GeeksforGeeks βTopological Sortingβ practice set, HackerRank problems tagged βTopological Sort.β
14. Common Mistakes
- Attempting topological sort on a graph that might have cycles without first checking/handling that case β always design for the βno valid order existsβ possibility.
- Using 2-state visited tracking for DFS-based cycle detection instead of 3-state (unvisited/in-progress/finished), causing false positives on legitimately convergent (non-cyclic) paths.
- Forgetting to iterate over all vertices as potential starting points (for disconnected graphs) in the DFS-based approach.
- Confusing push order with the final answer in the DFS-based method β the stack must be popped (or the push list reversed) to get the correct order.
- Not decrementing in-degree correctly or decrementing the wrong vertexβs in-degree in Kahnβs algorithm.
15. Summary
Key takeaways:
- Topological sort produces a valid βdependency-respectingβ order for a DAG β and both standard algorithms (Kahnβs/BFS-based and DFS-based) are simple extensions of traversals already covered in Chapter 10.
- Cycle detection falls out naturally from both algorithms β an unsatisfiable dependency set (a cycle) is detected as a side effect, not as separate extra work.
- Multiple valid orders often exist; if a specific tie-breaking order matters, additional constraints (like a min-heap for lexicographic order) must be layered on top.
Complexity recap:
| Algorithm | Time | Space |
|---|---|---|
| Kahnβs (BFS-based) | O(V + E) | O(V) |
| DFS-based | O(V + E) | O(V) |
Decision guideline: Use topological sort whenever you have a βmust happen beforeβ dependency graph and need either a valid processing order or a way to detect unsatisfiable (cyclic) dependencies β build systems, task scheduling, course planning, package installation order.
Next chapter: 12_minimum_spanning_tree.md β Kruskalβs and Primβs algorithms.
Chapter 12: Minimum Spanning Tree (Kruskalβs & Primβs)
Study time: ~6-7 hours | Prerequisite: Graphs, Heap, basic Union-Find concept (introduced here, detailed fully in the DSU chapter) | Difficulty: Intermediate-Advanced
1. Introduction
Definition: A Spanning Tree of a connected, undirected graph is a subset of its edges that connects all vertices with no cycles (exactly V-1 edges for V vertices). A Minimum Spanning Tree (MST) is the spanning tree whose total edge weight is as small as possible.
Purpose: To find the cheapest way to connect every vertex in a weighted graph β the minimum total cost network that still reaches everywhere.
Real-world analogy: A telecom company wants to lay fiber-optic cable connecting every city in a region, minimizing total cable length, while still being able to reach every city (directly or through other cities). An MST is exactly this β the cheapest possible fully-connected network, with no redundant/wasteful extra connections (a cycle would mean youβve spent money on a redundant path).
Motivation: Given a network with costs on every possible connection, connecting everything to everything is wasteful. We want minimum total cost while preserving full connectivity β this is the MST problem, and it comes up any time βconnect everything as cheaply as possibleβ is the goal.
History: Kruskalβs algorithm was published in 1956; Primβs was independently discovered by JarnΓk in 1930 and rediscovered by Prim in 1957 β both remain the standard MST algorithms taught today, over 60 years later.
2. Why Do We Need It?
Problem it solves: Minimizing total connection cost while guaranteeing full connectivity, with no wasted (redundant/cyclic) edges.
Why simpler approaches fail: Trying every possible subset of edges to find the cheapest connected one is exponential (2^E possibilities) β completely infeasible for any real-sized graph. MST algorithms exploit a key mathematical property (the βcut propertyβ β the cheapest edge crossing any partition of vertices is always safe to include) to build the answer greedily in polynomial time.
Trade-offs:
- You gain a provably optimal (minimum total weight) connected structure, computed efficiently β O(E log V) or better.
- The requirement is that the graph must be connected to start with (an MST of a disconnected graph doesnβt exist in the traditional sense β youβd get a βminimum spanning forestβ instead, one tree per connected component).
3. Internal Working
Example weighted graph:
A
4/ \2
B C
3| 1/ \5
D-----E
Edges: A-B(4), A-C(2), B-D(3), C-D(1), C-E(5), D-E(β¦ letβs just say D-E isnβt directly connected here for simplicity, keep it as above)
Kruskalβs Algorithm β βsort all edges, greedily add the cheapest that doesnβt create a cycleβ:
- Sort all edges by weight: C-D(1), A-C(2), B-D(3), A-B(4), C-E(5).
- Add C-D(1) β connects C and D, no cycle. MST so far: {C-D}.
- Add A-C(2) β connects A to the {C,D} group, no cycle. MST so far: {C-D, A-C}.
- Add B-D(3) β connects B to the {A,C,D} group, no cycle. MST so far: {C-D, A-C, B-D}.
- Consider A-B(4) β but A and B are already connected (both in the same group via C-D and A-C and B-D) β adding this would create a cycle β skip.
- Add C-E(5) β connects E to the group, no cycle. MST so far: {C-D, A-C, B-D, C-E}.
- Done β 4 edges connect all 5 vertices (V-1 = 4 β).
Total weight: 1+2+3+5 = 11.
The βno cycleβ check is exactly what Disjoint Set Union (Union-Find) is built for β each vertex starts in its own set; adding an edge merges two sets; if an edgeβs two endpoints are already in the same set, adding it would create a cycle, so itβs skipped. (Full DSU implementation details are in the Advanced Structures chapter β here, we use it as a tool.)
Primβs Algorithm β βgrow one tree from a starting vertex, always adding the cheapest edge that extends the treeβ:
- Start at A. Tree = {A}. Available edges from the tree: A-B(4), A-C(2).
- Add the cheapest: A-C(2). Tree = {A, C}. Available edges: A-B(4), C-D(1), C-E(5).
- Add the cheapest: C-D(1). Tree = {A, C, D}. Available edges: A-B(4), C-E(5), D-B(3).
- Add the cheapest: D-B(3). Tree = {A, C, D, B}. Available edges: A-B(4, but both endpoints already in tree β discard), C-E(5).
- Add C-E(5). Tree = {A, C, D, B, E}. Done.
Total weight: 2+1+3+5 = 11 β same total as Kruskalβs (MST weight is unique even if the specific edge set could theoretically differ with ties, and here it happens to be the identical set too).
Primβs naturally uses a Min-Heap to always efficiently retrieve βthe cheapest available edge extending the current treeβ β the direct link back to the Heap chapter.
4. Operations
Kruskalβs Algorithm:
- Sort all E edges by weight β O(E log E).
- Initialize DSU with each vertex in its own set β O(V).
- For each edge (in increasing weight order): if its two endpoints are in different sets, union them and add the edge to the MST; otherwise skip (it would form a cycle).
- Stop early once V-1 edges have been added (optional optimization).
Primβs Algorithm:
- Start with any vertex in the βtree so far,β and all other vertices βoutside.β
- Maintain a Min-Heap of candidate edges (weight, destination vertex) crossing from inside the tree to outside.
- Repeatedly extract the minimum-weight edge; if its destination is still outside the tree, add it to the MST and add that vertexβs new edges to the heap.
- If the destination is already inside the tree (a stale/outdated heap entry), discard it and continue.
Edge case for both: if the input graph is disconnected, neither algorithm can produce a single spanning tree β Kruskalβs will simply stop with fewer than V-1 edges (having exhausted all edges that donβt form a cycle within isolated components); Primβs, starting from one vertex, will never reach vertices in other components at all.
5. Time & Space Complexity
| Algorithm | Time Complexity | Space Complexity | Best suited for |
|---|---|---|---|
| Kruskalβs | O(E log E) β dominated by sorting edges | O(V) for DSU + O(E) for edge list | Sparse graphs (few edges relative to vertices) |
| Primβs (with Min-Heap) | O(E log V) | O(V) for heap + visited tracking | Dense graphs (many edges relative to vertices) |
Why these hold:
- Kruskalβs cost is dominated by the initial sort β O(E log E). The subsequent DSU operations (union/find) are nearly O(1) amortized each (using path compression and union by rank, detailed in the DSU chapter), so E union/find operations add only O(E) or O(E log*V) β negligible next to the sort.
- Primβs uses a Min-Heap to always extract the cheapest crossing edge in O(log V) (or O(log E), same order), and each of the E edges is pushed into the heap at most once β giving O(E log V) total.
- Kruskalβs tends to be simpler and often faster in practice for sparse graphs (E close to V) since sorting a smaller edge list is cheap; Primβs (with a good heap) tends to edge out for dense graphs (E close to VΒ²) since it never needs to sort the (much larger) full edge list upfront.
6. Advantages
- Both provably produce a globally minimum total weight spanning tree β not just a locally good one β thanks to the cut propertyβs greedy-choice guarantee.
- Both run in polynomial time (E log E or E log V), vastly better than the exponential brute-force alternative.
- Kruskalβs is conceptually simple once DSU is understood β βsort, then greedily skip cycles.β
- Primβs naturally extends to streaming/incremental scenarios where the graph is discovered edge by edge.
7. Disadvantages
- Only defined for connected graphs (or must be run per-component for disconnected ones, yielding a βminimum spanning forestβ).
- Kruskalβs requires sorting all edges upfront β potentially wasteful if you only need a partial answer or the graph is extremely large.
- Primβs, in its naive (non-heap) form, is O(VΒ²) β the heap-based version requires more implementation complexity to get the O(E log V) improvement.
- Neither directly gives the shortest path between two specific vertices β a completely different problem (see the next chapter) that MST is sometimes mistakenly conflated with.
8. Real-World Applications
- Networking: Designing minimum-cost network topologies (telecom cable layouts, computer network backbones) connecting all required locations.
- Utility Grids: Minimum-cost electrical grid or pipeline layout connecting all service points.
- Cluster Analysis: Some clustering algorithms use MST-based approaches (e.g., single-linkage clustering is directly related to Kruskalβs algorithmβs edge-processing order).
- Image Segmentation: Certain computer vision algorithms use MST-based region-growing techniques.
- Circuit Design: Minimizing wire length connecting circuit components.
- Approximation Algorithms: MST is a building block in approximation algorithms for other NP-hard problems (e.g., a 2-approximation for the Traveling Salesman Problem via MST-based construction).
9. Implementation (C++17)
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <numeric>
// A minimal Union-Find used by Kruskal's algorithm.
// (Full details β path compression, union by rank/size β covered in the DSU chapter.)
class UnionFind {
private:
std::vector<int> parent;
public:
UnionFind(int n) : parent(n) {
std::iota(parent.begin(), parent.end(), 0); // each vertex is its own parent initially
}
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]); // path compression
return parent[x];
}
bool unite(int x, int y) {
int rx = find(x), ry = find(y);
if (rx == ry) return false; // already connected β this edge would form a cycle
parent[rx] = ry;
return true;
}
};
struct Edge {
int u, v, weight;
};
// Kruskal's Algorithm. O(E log E).
std::vector<Edge> kruskalMST(int numVertices, std::vector<Edge> edges) {
std::sort(edges.begin(), edges.end(),
[](const Edge& a, const Edge& b) { return a.weight < b.weight; });
UnionFind uf(numVertices);
std::vector<Edge> mst;
for (const Edge& e : edges) {
if (uf.unite(e.u, e.v)) { // returns true only if u and v were in different sets
mst.push_back(e); // safe to add β no cycle created
}
if (static_cast<int>(mst.size()) == numVertices - 1) break; // MST complete
}
return mst;
}
// Prim's Algorithm using a Min-Heap. O(E log V).
std::vector<Edge> primMST(int numVertices, const std::vector<std::vector<std::pair<int,int>>>& adjList) {
// adjList[u] = list of (neighbor, weight)
std::vector<bool> inMST(numVertices, false);
// Min-heap of (weight, to_vertex, from_vertex)
std::priority_queue<std::tuple<int,int,int>, std::vector<std::tuple<int,int,int>>, std::greater<>> pq;
std::vector<Edge> mst;
pq.push({0, 0, -1}); // start at vertex 0, no "from" vertex
while (!pq.empty() && static_cast<int>(mst.size()) < numVertices - 1) {
auto [weight, u, from] = pq.top();
pq.pop();
if (inMST[u]) continue; // stale entry β u already added via a cheaper/earlier path
inMST[u] = true;
if (from != -1) mst.push_back({from, u, weight}); // skip the synthetic starting entry
for (auto [neighbor, w] : adjList[u]) {
if (!inMST[neighbor]) {
pq.push({w, neighbor, u});
}
}
}
return mst;
}
// Example usage
int main() {
// Graph: A=0, B=1, C=2, D=3, E=4
std::vector<Edge> edges = {
{0,1,4}, {0,2,2}, {1,3,3}, {2,3,1}, {2,4,5}
};
auto mstK = kruskalMST(5, edges);
int totalK = 0;
std::cout << "Kruskal's MST edges: ";
for (auto& e : mstK) { std::cout << "(" << e.u << "-" << e.v << ":" << e.weight << ") "; totalK += e.weight; }
std::cout << "\nTotal weight: " << totalK << "\n"; // 11
// Build adjacency list for Prim's from the same edges (undirected).
std::vector<std::vector<std::pair<int,int>>> adjList(5);
for (auto& e : edges) {
adjList[e.u].push_back({e.v, e.weight});
adjList[e.v].push_back({e.u, e.weight});
}
auto mstP = primMST(5, adjList);
int totalP = 0;
std::cout << "Prim's MST edges: ";
for (auto& e : mstP) { std::cout << "(" << e.u << "-" << e.v << ":" << e.weight << ") "; totalP += e.weight; }
std::cout << "\nTotal weight: " << totalP << "\n"; // 11 β same total as Kruskal's
return 0;
}
10. Code Walkthrough
UnionFind::findwith path compression:parent[x] = find(parent[x])doesnβt just find the root β it rewires every visited node directly to the root on the way, so futurefindcalls on those same nodes are much faster. This single line is what keeps Kruskalβs DSU operations nearly O(1) amortized.UnionFind::unite: Returnsfalseifxandyare already in the same set (same root) β this return value is exactly what Kruskalβs main loop uses to decide βwould this edge create a cycle?β- Kruskalβs sort + greedy loop: Sorting once upfront (O(E log E)) lets the rest of the algorithm simply walk the list in order, trusting that any edge reached is the cheapest remaining option β this is the βgreedyβ part, justified by the cut property (a proof beyond this guideβs scope, but intuitively: the globally cheapest edge can never be wrong to include, since excluding it and using a more expensive alternative to connect the same two components can only increase total weight).
- Primβs
priority_queueof(weight, to, from)tuples: Ordered by weight (smallest first, viastd::greater<>) β every time we pop, we get the cheapest known edge crossing into an unvisited vertex. TheinMST[u]check on pop (not on push) handles the fact that a vertex might have multiple candidate edges pushed before any of them get processed β we only care about the first (cheapest) one that gets popped; subsequent (more expensive, βstaleβ) entries for the same vertex are simply discarded. from != -1check: The synthetic starting entry(0, 0, -1)seeds the heap without corresponding to a real edge β this check filters it out of the final edge list.
Common mistakes to watch for here:
- Forgetting path compression in
find, making Kruskalβs DSU operations degrade toward O(n) each in the worst case. - In Primβs, checking
inMSTbefore pushing instead of after popping β this can miss the cheapest edge if a more expensive one to the same vertex happens to be pushed and popped first (actually the check should be on pop, exactly as shown β pushing extra βsoon to be staleβ entries is fine and expected). - Assuming Kruskalβs and Primβs always produce the identical edge set β they always produce the same total weight, but with weight ties, the specific edges chosen can differ.
11. Dry Run
Graph: A-B(4), A-C(2), B-D(3), C-D(1), C-E(5). Kruskalβs, step by step:
| Step | Edge considered | Same set already? | Action | MST so far |
|---|---|---|---|---|
| 1 | C-D (1) | No (C,D separate) | Add | {C-D} |
| 2 | A-C (2) | No (A separate, C in {C,D}) | Add | {C-D, A-C} |
| 3 | B-D (3) | No (B separate, D in {A,C,D}) | Add | {C-D, A-C, B-D} |
| 4 | A-B (4) | Yes (A and B both now in {A,B,C,D}) | Skip (would cycle) | unchanged |
| 5 | C-E (5) | No (E separate) | Add | {C-D, A-C, B-D, C-E} |
4 edges for 5 vertices β MST complete. Total: 1+2+3+5 = 11. β (Matches the code output.)
12. Interview Questions
Conceptual:
- Explain the βcut propertyβ that justifies both Kruskalβs and Primβs greedy choices.
- When would you prefer Kruskalβs over Primβs, and vice versa?
- What happens if you run Kruskalβs or Primβs on a disconnected graph?
- Why does Kruskalβs need Union-Find specifically, rather than a simple visited array?
- Is the Minimum Spanning Tree always unique? Under what condition might there be multiple valid MSTs with the same total weight?
Coding:
- Implement Kruskalβs Algorithm using Union-Find.
- Implement Primβs Algorithm using a Min-Heap.
- Min Cost to Connect All Points (LeetCode 1584) β MST on a complete graph of points.
- Find Critical and Pseudo-Critical Edges in MST (LeetCode 1489).
- Optimize Water Distribution in a Village (LeetCode 1168) β MST with virtual source node.
Follow-ups / interviewer traps:
- βWhat if edge weights can be negative β does MST still work correctly?β (yes β MST algorithms work fine with negative weights, unlike some shortest-path algorithms covered next chapter)
- βHow would you find the second-best MST?β (tests deeper algorithmic thinking β typically involves trying to swap each MST edge with the next-best alternative)
- βCan you adapt Primβs to run without a heap, and whatβs the complexity then?β (O(VΒ²) β tests understanding of the heapβs specific contribution)
13. Practice Problems
Easy
- Find if Path Exists in Graph (LeetCode 1971) β foundational connectivity check
Medium
- Min Cost to Connect All Points (LeetCode 1584)
- Connecting Cities With Minimum Cost (LeetCode 1135)
- Optimize Water Distribution in a Village (LeetCode 1168)
Hard
- Find Critical and Pseudo-Critical Edges in MST (LeetCode 1489)
- Minimum Cost to Make at Least One Valid Path in a Grid (related connectivity/shortest-path hybrid)
Also recommended: GeeksforGeeks βMinimum Spanning Treeβ practice set, Codeforces problems tagged dsu + graphs.
14. Common Mistakes
- Forgetting to sort edges before running Kruskalβs greedy loop β the entire correctness argument depends on always considering the next-cheapest remaining edge.
- Using a plain visited array instead of Union-Find in Kruskalβs, which canβt efficiently detect βthese two vertices are already connected through some indirect pathβ (thatβs precisely what DSU is for).
- Not handling stale heap entries in Primβs β forgetting the
if (inMST[u]) continue;check after popping leads to incorrect edge counts or double-processing. - Assuming MST gives shortest paths between arbitrary vertex pairs β it does not; MST minimizes total connection cost, not any individual pairwise path (thatβs the Shortest Path problem, next chapter).
- Running MST algorithms on disconnected graphs without checking connectivity first, and being surprised when fewer than V-1 edges result.
15. Summary
Key takeaways:
- An MST is the minimum-total-weight way to connect every vertex in a graph, with no redundant (cycle-forming) edges.
- Kruskalβs greedily picks the globally cheapest remaining edge that doesnβt form a cycle (needs sorting + Union-Find); Primβs greedily grows one tree, always adding the cheapest edge that extends it (needs a Min-Heap).
- Both are correct because of the cut property β a proof that the cheapest edge crossing any cut is always safe to include.
- Kruskalβs tends to suit sparse graphs; Primβs tends to suit dense graphs, though both are broadly applicable.
Complexity recap:
| Algorithm | Time |
|---|---|
| Kruskalβs | O(E log E) |
| Primβs (heap-based) | O(E log V) |
Decision guideline: Use Kruskalβs when the edge list is naturally available and relatively small (sparse graphs), or when youβre already thinking in terms of Union-Find. Use Primβs when working with adjacency-list-heavy, dense graphs, or when you want to grow the MST incrementally from a specific starting point.
Next chapter: 13_shortest_path.md β Dijkstraβs and Bellman-Fordβs algorithms.
Chapter 13: Shortest Path (Dijkstraβs & Bellman-Fordβs)
Study time: ~7-8 hours | Prerequisite: Graphs, Heap | Difficulty: Intermediate-Advanced
1. Introduction
Definition: The single-source shortest path problem asks: given a weighted graph and a starting vertex, what is the minimum total-weight path from the start to every other vertex? Dijkstraβs Algorithm solves this efficiently when all edge weights are non-negative. Bellman-Fordβs Algorithm solves the more general case, including graphs with negative edge weights, and can detect negative-weight cycles (where no shortest path even exists, since you could loop forever accumulating negative cost).
Purpose: To find the cheapest route between locations in a weighted network β not just βfewest hopsβ (thatβs BFS, for unweighted graphs) but βlowest total cost,β where different edges can have very different costs.
Real-world analogy: A GPS navigation app doesnβt just count intersections β it finds the route with the lowest total time or distance, where some road segments (edges) take much longer than others. Dijkstraβs is exactly this: βalways expand toward whichever reachable point currently has the cheapest known total cost so far.β
Motivation: BFS (Chapter 10) finds the shortest path in unweighted graphs (or graphs where every edge costs exactly the same). Real-world networks almost never have uniform costs β flights have different prices, roads have different travel times, network links have different latencies. We need an algorithm that accounts for these varying weights.
History: Dijkstraβs algorithm was devised by Edsger Dijkstra in 1956 (published 1959) β one of the most famous and widely taught algorithms in all of computer science. Bellman-Fordβs was developed independently by Richard Bellman and Lester Ford Jr. around the same era, specifically to handle negative weights that Dijkstraβs cannot.
2. Why Do We Need It?
Problem it solves: Finding minimum-total-cost paths in a weighted graph, from one source to all (or one specific) destination(s).
Why BFS is insufficient: BFS treats every edge as costing exactly 1 β it has no concept of βthis edge is more expensive than that one.β Running plain BFS on a weighted graph can return a path with more total weight but fewer edges, which is simply the wrong answer to βwhatβs cheapest?β
Trade-offs:
- Dijkstraβs gains excellent performance β O(E log V) with a heap β but requires non-negative edge weights; it can silently produce wrong answers on a graph with negative edges (it greedily βfinalizesβ a vertexβs shortest distance once popped from the heap, an assumption that breaks if a not-yet-explored negative edge could later reduce that distance further).
- Bellman-Fordβs handles negative weights correctly (and detects negative cycles) but is slower β O(VΒ·E) β because it must be more conservative, re-checking all edges repeatedly rather than greedily trusting any single vertexβs distance as final.
3. Internal Working
Dijkstraβs Algorithm β βalways expand the closest known vertex next,β using a Min-Heap:
Graph (directed, weighted):
A --4--> B
A --1--> C
C --2--> B
C --5--> D
B --1--> D
Start: A. dist[A]=0, all others = infinity.
Step 1: Heap: [(0,A)]. Pop A (dist 0). Relax neighbors:
B: dist[B] = min(inf, 0+4) = 4. Push (4,B).
C: dist[C] = min(inf, 0+1) = 1. Push (1,C).
Step 2: Heap: [(1,C),(4,B)]. Pop C (dist 1, the smallest). Relax neighbors:
B: candidate = dist[C]+2 = 1+2 = 3. 3 < current dist[B]=4 β UPDATE dist[B]=3. Push (3,B).
D: candidate = dist[C]+5 = 1+5 = 6. dist[D]=6. Push (6,D).
Step 3: Heap: [(3,B),(4,B),(6,D)]. Pop B (dist 3 β the smaller of the two B entries). Relax neighbors:
D: candidate = dist[B]+1 = 3+1 = 4. 4 < current dist[D]=6 β UPDATE dist[D]=4. Push (4,D).
Step 4: Heap: [(4,B)(stale),(4,D),(6,D)(stale)]. Pop (4,B) β but B already finalized at dist 3 β STALE, discard.
Step 5: Pop (4,D) β finalize dist[D]=4.
Step 6: Remaining heap entries are all stale, discard.
Final: dist[A]=0, dist[B]=3, dist[C]=1, dist[D]=4.
Notice: the direct AβB edge (weight 4) looked cheapest at first, but going AβCβB (1+2=3) turned out cheaper β Dijkstraβs correctly finds this by always expanding the globally cheapest known frontier vertex next, not just greedily following the first edge seen.
Bellman-Fordβs Algorithm β βrelax every edge, V-1 times, guaranteed to convergeβ:
Same graph. dist[A]=0, others=infinity.
Pass 1: relax every edge once, in any order (say: A-B, A-C, C-B, C-D, B-D):
A-B: dist[B]=min(inf,0+4)=4
A-C: dist[C]=min(inf,0+1)=1
C-B: dist[B]=min(4,1+2)=3 β improved!
C-D: dist[D]=min(inf,1+5)=6
B-D: dist[D]=min(6,3+1)=4 β improved!
Pass 2: relax every edge again β check if anything STILL improves:
A-B: 0+4=4, not better than 3. A-C: 0+1=1, no change. C-B: 1+2=3, no change.
C-D: 1+5=6, not better than 4. B-D: 3+1=4, no change.
Nothing improved β we could stop early here.
(In the worst case, up to V-1 passes are needed β this graph converged faster.)
Final: same result as Dijkstra's β dist[A]=0, dist[B]=3, dist[C]=1, dist[D]=4.
Why V-1 passes are the guaranteed upper bound: the shortest path between any two vertices in a graph with V vertices can use at most V-1 edges (a simple path visits each vertex at most once). Each full pass of relaxing every edge is guaranteed to correctly extend the βsettledβ shortest-path length by at least one more edge β so after V-1 passes, every shortest path (however many edges it uses, up to V-1) is guaranteed correct.
Negative cycle detection (Bellman-Ford only): run one extra (V-th) pass β if any distance still improves, a negative-weight cycle exists somewhere reachable from the source (since a legitimate shortest path can never need more than V-1 edges; still finding improvement means youβre looping around a negative cycle to keep reducing βcostβ indefinitely).
4. Operations
Dijkstraβs:
- Initialize
dist[source] = 0, all others = infinity. - Push
(0, source)onto a Min-Heap. - Repeatedly pop the minimum-distance vertex; if already finalized (visited), skip (stale entry).
- Otherwise, finalize it, and relax every outgoing edge: for each neighbor, if
dist[current] + edge_weight < dist[neighbor], updatedist[neighbor]and push the new candidate onto the heap. - Continue until the heap is empty.
- Edge case: unreachable vertices retain
dist = infinity.
Bellman-Fordβs:
- Initialize
dist[source] = 0, all others = infinity. - Repeat V-1 times: for every edge (u,v,weight) in the graph, relax it β if
dist[u] + weight < dist[v], updatedist[v]. - Optional (V-th pass): if any edge can still be relaxed, a negative cycle exists reachable from the source.
- Edge case: if a vertex is unreachable, its distance simply never updates from infinity β no special handling needed.
5. Time & Space Complexity
| Algorithm | Time Complexity | Space Complexity | Handles negative weights? |
|---|---|---|---|
| Dijkstraβs (Min-Heap) | O(E log V) | O(V) for distances + heap | No |
| Bellman-Fordβs | O(V Β· E) | O(V) for distances | Yes (and detects negative cycles) |
Why these hold:
- Dijkstraβs processes each vertex once (finalized when popped) and each edge is relaxed (potentially pushing a heap entry) at most once per edge traversal β giving O(E) heap operations, each O(log V) β total O(E log V).
- Bellman-Fordβs must relax every edge, V-1 times, in the worst case β giving O(V Β· E). This is significantly slower than Dijkstraβs for large graphs, which is exactly the price paid for correctness under negative weights.
- Why Dijkstraβs breaks with negative weights (the key conceptual point): Dijkstraβs finalizes a vertexβs distance the moment itβs popped from the heap, trusting that no future discovery could ever improve it β this trust is only valid because, with non-negative weights, any path found later can only be longer (weight only adds, never subtracts). A single negative edge could let a longer hop-count path have a lower total weight, discovered only after a vertex was already (wrongly) finalized.
6. Advantages
Dijkstraβs:
- Efficient β O(E log V) scales well even for large sparse graphs.
- Straightforward extension of BFSβs βexpand the frontierβ idea, just prioritized by actual cost instead of hop count.
Bellman-Fordβs:
- Correctly handles negative edge weights, which Dijkstraβs cannot.
- Detects negative-weight cycles β valuable in its own right (e.g., flagging arbitrage opportunities in currency exchange graphs, or invalid/exploitable cost models).
- Simpler to implement correctly (no heap, no βstale entryβ subtlety) β just a straightforward nested loop.
7. Disadvantages
Dijkstraβs: produces silently wrong answers on graphs with negative edges (no error, no crash β just an incorrect result) β a genuinely dangerous failure mode if youβre not certain about your input data.
Bellman-Fordβs: significantly slower (O(VΒ·E) vs O(E log V)) β impractical for very large graphs where Dijkstraβs would suffice.
8. Real-World Applications
- GPS/Navigation: Finding fastest/shortest driving, walking, or transit routes (Dijkstraβs, or more advanced variants like A* which add heuristics).
- Networking: Routing protocols (OSPF β Open Shortest Path First β literally uses Dijkstraβs algorithm to compute routing tables).
- Airlines/Logistics: Cheapest flight/shipping route calculations, sometimes with negative βweightsβ representing discounts or rebates, requiring Bellman-Ford.
- Finance: Detecting arbitrage opportunities in currency exchange (a cycle of trades that nets a profit corresponds to a negative-weight cycle in a graph of exchange rates β Bellman-Fordβs cycle detection is directly applicable).
- Telecommunications: Finding lowest-latency paths through a network.
- Game Development: Pathfinding in weighted terrain (different terrain types cost different movement points).
9. Implementation (C++17)
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
const int INF = std::numeric_limits<int>::max();
struct WeightedEdge {
int to;
int weight;
};
// Dijkstra's Algorithm. O(E log V). Requires non-negative weights.
std::vector<int> dijkstra(int numVertices, const std::vector<std::vector<WeightedEdge>>& adjList, int source) {
std::vector<int> dist(numVertices, INF);
dist[source] = 0;
// Min-heap of (distance, vertex)
std::priority_queue<std::pair<int,int>, std::vector<std::pair<int,int>>, std::greater<>> pq;
pq.push({0, source});
std::vector<bool> finalized(numVertices, false);
while (!pq.empty()) {
auto [d, u] = pq.top();
pq.pop();
if (finalized[u]) continue; // stale entry β u already has its final shortest distance
finalized[u] = true;
for (const WeightedEdge& edge : adjList[u]) {
int candidate = d + edge.weight;
if (candidate < dist[edge.to]) {
dist[edge.to] = candidate; // relax: found a cheaper path to edge.to
pq.push({candidate, edge.to});
}
}
}
return dist;
}
struct SimpleEdge {
int from, to, weight;
};
// Bellman-Ford's Algorithm. O(V * E). Handles negative weights; detects negative cycles.
// Returns {distances, hasNegativeCycle}.
std::pair<std::vector<int>, bool> bellmanFord(int numVertices, const std::vector<SimpleEdge>& edges, int source) {
std::vector<int> dist(numVertices, INF);
dist[source] = 0;
// Relax all edges V-1 times β guaranteed sufficient for any negative-cycle-free graph.
for (int i = 0; i < numVertices - 1; ++i) {
for (const SimpleEdge& e : edges) {
if (dist[e.from] != INF && dist[e.from] + e.weight < dist[e.to]) {
dist[e.to] = dist[e.from] + e.weight;
}
}
}
// One more pass: if anything STILL improves, a negative cycle exists.
bool hasNegativeCycle = false;
for (const SimpleEdge& e : edges) {
if (dist[e.from] != INF && dist[e.from] + e.weight < dist[e.to]) {
hasNegativeCycle = true;
break;
}
}
return {dist, hasNegativeCycle};
}
// Example usage
int main() {
// Graph: A=0, B=1, C=2, D=3
// A->B(4), A->C(1), C->B(2), C->D(5), B->D(1)
std::vector<std::vector<WeightedEdge>> adjList(4);
adjList[0] = {{1,4}, {2,1}};
adjList[2] = {{1,2}, {3,5}};
adjList[1] = {{3,1}};
auto distDijkstra = dijkstra(4, adjList, 0);
std::cout << "Dijkstra's distances from A: ";
for (int d : distDijkstra) std::cout << d << " ";
std::cout << "\n"; // 0 3 1 4 (matches the section 3 dry run)
std::vector<SimpleEdge> edges = {
{0,1,4}, {0,2,1}, {2,1,2}, {2,3,5}, {1,3,1}
};
auto [distBF, hasNegCycle] = bellmanFord(4, edges, 0);
std::cout << "Bellman-Ford's distances from A: ";
for (int d : distBF) std::cout << d << " ";
std::cout << "\nNegative cycle? " << (hasNegCycle ? "yes" : "no") << "\n"; // 0 3 1 4, no
// Now with a NEGATIVE edge Dijkstra's would get wrong: add C->B(-3) instead of +2
std::vector<SimpleEdge> edgesNeg = {
{0,1,4}, {0,2,1}, {2,1,-3}, {2,3,5}, {1,3,1}
};
auto [distBFNeg, hasNegCycle2] = bellmanFord(4, edgesNeg, 0);
std::cout << "Bellman-Ford's with negative edge: ";
for (int d : distBFNeg) std::cout << d << " ";
std::cout << "\n"; // 0 -2 1 -1 β correctly propagates the negative weight
return 0;
}
10. Code Walkthrough
- Dijkstraβs
finalizedarray + βcheck on pop, not on pushβ: Exactly the same pattern as Primβs algorithm in the previous chapter β because a vertex can have multiple candidate distances pushed onto the heap before the cheapest one is actually popped and processed, we must discard stale (already-finalized) entries after popping, not try to prevent them at push time. - The relax operation (
if candidate < dist[edge.to]): this single line β βis going through the current vertex cheaper than what I already knew?β β is the fundamental operation both algorithms are built entirely out of. Dijkstraβs does it opportunistically (only from the current cheapest frontier vertex); Bellman-Fordβs does it exhaustively (every edge, every pass). - Bellman-Fordβs
numVertices - 1outer loop: This is the mathematically guaranteed bound from section 3 β any shortest path uses at most V-1 edges, so V-1 full relaxation passes are always sufficient (assuming no negative cycle). - The extra (V-th) pass for cycle detection: If a distance can still improve after V-1 guaranteed-sufficient passes, the only explanation is a negative cycle letting costs decrease without bound β this check is simply βrun the exact same relaxation logic one more time and see if anything changes.β
dist[e.from] != INFguard: Prevents integer overflow/nonsensical arithmetic from adding a weight to an βunreachableβ (infinity) distance β a subtle but important correctness detail, especially in real code whereINFis a large finite sentinel value, not literal infinity.
Common mistakes to watch for here:
- Using Dijkstraβs on a graph that might have negative weights β it wonβt crash, it will just silently return a wrong answer, which is far more dangerous than an error.
- Forgetting the
INFguard in Bellman-Fordβs relaxation check, causing overflow when adding a weight to an unreachable vertexβs sentinel value. - Running only V-2 (one too few) Bellman-Ford passes, missing the longest possible shortest path.
- Checking
finalizedbefore pushing in Dijkstraβs instead of after popping β this can (rarely, but incorrectly) skip pushing a genuinely useful candidate.
11. Dry Run
Already fully traced in section 3 for both algorithms on the same example graph β both correctly converge on dist = [0, 3, 1, 4] for A, B, C, D respectively. The key comparative dry-run insight: Dijkstraβs reaches this answer in one efficient heap-guided pass (never revisiting a finalized vertex), while Bellman-Fordβs reaches the same answer by brute-force repeating full edge relaxation passes β slower, but robust enough to also correctly handle the negative-edge variant shown in the codeβs third example (dist = [0, -2, 1, -1]), which Dijkstraβs would get wrong if naively run on that same graph.
12. Interview Questions
Conceptual:
- Why does Dijkstraβs algorithm fail on graphs with negative edge weights? Walk through a concrete counterexample.
- Why does Bellman-Fordβs need exactly V-1 passes (and why is a V-th pass useful)?
- Compare the time complexities of Dijkstraβs and Bellman-Fordβs, and explain the source of the difference.
- How would you reconstruct the actual shortest path (not just distance) from either algorithmβs output? (Track a
predecessorarray alongside distances.) - Whatβs the relationship between BFS and Dijkstraβs algorithm? (BFS is Dijkstraβs specialized to uniform edge weight = 1, where a plain queue suffices instead of a priority queue.)
Coding:
- Implement Dijkstraβs algorithm with path reconstruction.
- Implement Bellman-Fordβs algorithm with negative cycle detection.
- Network Delay Time β Dijkstraβs applied directly (LeetCode 743).
- Cheapest Flights Within K Stops β a Bellman-Ford-style bounded-relaxation variant.
- Path with Maximum Probability β Dijkstraβs variant with multiplicative (not additive) edge βweights.β
Follow-ups / interviewer traps:
- βWhat if you need shortest paths between ALL pairs of vertices, not just from one source?β (tests awareness of Floyd-Warshall, O(VΒ³), as the natural extension beyond this chapterβs scope)
- βYour graph has up to K allowed stops β how do you bound the search?β (tests adapting Bellman-Ford-style layered relaxation, exactly the Cheapest Flights problem above)
- βCan Dijkstraβs be used with a graph that has zero-weight edges?β (yes β zero is non-negative, works fine; the failure mode is specifically negative weights)
13. Practice Problems
Easy
- Find the City With the Smallest Number of Neighbors at a Threshold Distance (LeetCode 1334)
Medium
- Network Delay Time (LeetCode 743)
- Cheapest Flights Within K Stops (LeetCode 787)
- Path with Maximum Probability (LeetCode 1514)
Hard
- Swim in Rising Water (LeetCode 778) β Dijkstraβs-style with a twist
- Minimum Cost to Make at Least One Valid Path in a Grid (LeetCode 1368)
- Shortest Path Visiting All Nodes (LeetCode 847) β combines shortest path with bitmask state
Also recommended: GeeksforGeeks βShortest Path Algorithmsβ practice set, Codeforces problems tagged shortest-paths, and studying Floyd-Warshall as a natural follow-up for all-pairs shortest paths.
14. Common Mistakes
- Using Dijkstraβs on a graph that might have negative weights without verifying that assumption first β the single most dangerous mistake in this chapter, since it fails silently.
- Off-by-one in Bellman-Fordβs pass count β using V instead of V-1 (technically harmless extra work) or V-2 (genuinely wrong, may miss the longest valid shortest path).
- Forgetting the
INF/unreachable guard before adding to a distance, causing overflow or nonsensical relaxation. - Confusing βshortest pathβ with βminimum spanning treeβ β they solve different problems (MST minimizes total network cost; shortest path minimizes cost between two specific points) and can produce completely different edge sets on the same graph.
- Not handling the stale-heap-entry case in Dijkstraβs, leading to reprocessing already-finalized vertices (usually harmless due to the guard, but wasteful and a sign of misunderstanding if omitted).
15. Summary
Key takeaways:
- Dijkstraβs is the fast, standard choice (O(E log V)) for non-negative-weight shortest-path problems β think of it as βBFS with a Min-Heap instead of a Queue, prioritizing by cost instead of hop count.β
- Bellman-Fordβs is slower (O(VΒ·E)) but strictly more general β it correctly handles negative weights and can detect negative cycles, which fundamentally break Dijkstraβs greedy βfinalize on popβ assumption.
- Both are built from the same core βrelax an edgeβ operation β the difference is how systematically (Dijkstraβs: opportunistically via a heap; Bellman-Fordβs: exhaustively via repeated full passes) that relaxation is applied.
Complexity recap:
| Algorithm | Time | Negative weights? |
|---|---|---|
| Dijkstraβs | O(E log V) | No |
| Bellman-Fordβs | O(V Β· E) | Yes, plus cycle detection |
Decision guideline: Use Dijkstraβs whenever you can guarantee non-negative edge weights β itβs faster and simpler to reason about. Use Bellman-Fordβs when negative weights are possible, or when you specifically need to detect negative cycles (e.g., arbitrage detection). For all-pairs shortest paths (every vertex to every other), look beyond this chapter to Floyd-Warshall (O(VΒ³)).
Next: Advanced Data Structures β 14_segment_tree.md, 15_fenwick_tree.md, 16_disjoint_set_union.md, 17_skip_list.md, 18_bloom_filter.md, and the capstone 19_lru_cache.md. Say the word for the next 3.
Chapter 14: Segment Tree
Study time: ~7-9 hours | Prerequisite: Binary Tree, Recursion, Arrays | Difficulty: Advanced
1. Introduction
Definition: A Segment Tree is a binary tree built over an array where each node represents the aggregate (sum, min, max, gcd, etc.) of a contiguous range (segment) of the array. The root represents the whole array; each nodeβs two children split its range in half.
Purpose: To answer range queries (βwhatβs the sum/min/max of elements from index L to R?β) and support point or range updates, both in O(log n) β dramatically better than the O(n) a plain array requires for range queries.
Real-world analogy: Think of a companyβs org chart where every managerβs βtotal headcountβ is the sum of their direct reportsβ headcounts (recursively). If one employee joins or leaves, you only need to update the counts along that one employeeβs chain of managers up to the CEO β not recount the entire company from scratch. A Segment Tree is exactly this βhierarchical running totalβ idea applied to array ranges.
Motivation: A plain array answers βsum of range [L,R]β in O(n) (must add every element) or, with a prefix sum array, in O(1) β but a prefix sum array requires O(n) to update if any element changes (every prefix sum after that index must shift). A Segment Tree is the structure that supports both range queries and updates efficiently β the prefix-sum approach breaks down the moment updates are required.
History: Segment trees emerged from computational geometry research in the 1970s-80s, and became a competitive-programming staple due to their flexibility for arbitrary associative range operations.
2. Why Do We Need It?
Problem it solves: βQuery an aggregate over a range, AND update elementsβ β both efficiently, at the same time. This combination is what no simpler structure handles well.
Why previous structures are insufficient:
- Plain array: O(1) point update, but O(n) range query.
- Prefix sum array: O(1) range query, but O(n) point update (shifting all subsequent prefix sums).
- Fenwick Tree (next chapter): handles prefix sums and point updates in O(log n) elegantly, but is naturally suited to simpler aggregate operations (mainly sums/frequency counts) and is less flexible for complex custom range operations (range min/max, GCD, or operations needing lazy propagation for range updates).
Trade-offs:
- You gain O(log n) for both range queries and updates, plus flexibility for any associative operation (sum, min, max, gcd, XOR, custom combine function).
- You pay for it with roughly 4x the arrayβs memory (a common implementation convention, explained in section 3), and meaningfully more implementation complexity than a Fenwick Tree for the simple-sum case.
3. Internal Working
Array: [2, 4, 5, 7, 8, 9] (indices 0-5). Segment Tree for range SUM, built recursively β each node covers a range [lo, hi], and its value is the sum of that range:
[0,5]=35
/ \
[0,2]=11 [3,5]=24
/ \ / \
[0,1]=6 [2,2]=5 [3,4]=15 [5,5]=9
/ \ / \
[0,0]=2 [1,1]=4 [3,3]=7 [4,4]=8
Each internal nodeβs value = sum of its two children β exactly like the org-chart headcount analogy. Leaves correspond to individual array elements.
Array representation (common convention): stored in a flat array of size ~4n, where for a node at index i: left child = 2i+1, right child = 2i+2 (same indexing scheme as a Heap β Chapter 4 β though a Segment Tree isnβt a complete binary tree, so it needs roughly double the heapβs array size to safely accommodate all possible node positions).
Range query for sum([1,4]) β decompose the query range into segments that exactly match existing nodes, recursing only where necessary:
Query [1,4] against root [0,5]: partially overlaps β recurse into both children.
[0,2]: partially overlaps [1,4] β recurse into children.
[0,1]: partially overlaps β recurse.
[0,0]: outside [1,4] entirely β contribute 0, stop.
[1,1]: fully inside [1,4] β contribute value 4, stop (no need to go deeper!)
[2,2]: fully inside [1,4] β contribute value 5, stop.
[3,5]: partially overlaps [1,4] β recurse into children.
[3,4]: fully inside [1,4] β contribute value 15, stop.
[5,5]: outside [1,4] β contribute 0, stop.
Total: 4 + 5 + 15 = 24
Notice how, the moment a nodeβs range is fully inside the query range, recursion stops immediately (no need to descend further) β this βearly stop at full containmentβ is exactly why the query is O(log n) rather than O(n): at most O(log n) nodes are fully contained per level, and there are O(log n) levels.
Point update β update index 2 from 5 to 10, propagating the change up:
Leaf [2,2]: 5 β 10
Parent [0,2]: recompute as sum of children [0,1]=6 and [2,2]=10 β 16
Root [0,5]: recompute as sum of children [0,2]=16 and [3,5]=24 β 40
Only the O(log n) ancestors of the updated leaf need recomputation β everything else is untouched.
4. Operations
Build:
- Recursively split
[lo, hi]into[lo, mid]and[mid+1, hi], build each half, then combine (e.g., sum) their results into the current node. - O(n) total β every node is computed exactly once, and there are O(n) nodes total (roughly 2n-1 for a full binary tree over n leaves).
Range Query (e.g., sum/min/max over [L,R]):
- If the current nodeβs range is entirely outside [L,R], return the βidentityβ (0 for sum, +β for min, etc.) β contributes nothing.
- If the current nodeβs range is entirely inside [L,R], return its stored value directly β no need to recurse further.
- Otherwise (partial overlap), recurse into both children and combine their results.
- O(log n) β as shown in the dry run above.
Point Update:
- Recurse down to the specific leaf, update it, then recompute every ancestor on the way back up as the combination of its two children.
- O(log n) β only one path from root to leaf is touched.
Range Update (with Lazy Propagation β an important extension):
- Naively updating every element in a range one at a time would be O(range size Γ log n) β too slow for large ranges.
- Lazy propagation defers updates: mark a node as βpending an updateβ without immediately recursing into its children; only push the pending update down when that subtree is actually visited by a later query/update. This brings range updates down to O(log n) as well.
5. Time & Space Complexity
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Build | O(n) | O(n) (~4n array, common convention) |
| Range Query | O(log n) | O(log n) recursion stack |
| Point Update | O(log n) | O(log n) recursion stack |
| Range Update (with lazy propagation) | O(log n) | O(n) extra for the lazy array |
| Range Update (without lazy propagation, naive) | O(range size Γ log n) | β |
Why these hold:
- Build is O(n) because each of the ~2n-1 nodes is computed exactly once via a single combine operation from its two children β a classic βsum of a geometric-like recursive structureβ that totals linear work.
- Range Query is O(log n) because, at each level of the tree, the query range boundary can only βsplitβ the range into partial-overlap segments at most twice (once on the left edge, once on the right edge) β everything else is either fully inside (stop immediately) or fully outside (stop immediately). This bounds the number of nodes visited to O(log n) per level Γ O(log n) levelsβ¦ more precisely, it works out to O(log n) total visited nodes, not O(logΒ² n), due to how the partial-overlap nodes telescope.
- Point Update is O(log n) because it only touches the single root-to-leaf path, which has length equal to the treeβs height, O(log n).
6. Advantages
- O(log n) for both range queries and updates β the combination neither a plain array nor a prefix-sum array can offer simultaneously.
- Extremely flexible β works for any associative operation with an identity element (sum, min, max, GCD, XOR, custom combiners), unlike some more specialized structures.
- Lazy propagation extends it to efficient range updates (not just point updates), a capability few simpler structures have at all.
7. Disadvantages
- More complex to implement correctly than a Fenwick Tree, especially with lazy propagation.
- Roughly 4x memory overhead compared to the raw array (common array-based implementation convention) β though pointer-based or dynamically-sized variants can reduce this.
- Overkill for problems that only need simple prefix sums with point updates β a Fenwick Tree (next chapter) is simpler and sufficient there.
8. Real-World Applications
- Databases: Range-aggregate query optimization (e.g., βsum of sales between these datesβ) in specialized analytical engines.
- Competitive Programming: A staple for range-query problems β arguably the single most common βadvanced data structureβ in competitive programming contests.
- Computational Geometry: Interval/range problems (finding overlapping intervals, stabbing queries).
- Gaming/Graphics: Range-based collision or visibility queries over spatial data.
- Financial Systems: Real-time range aggregation over time-series data (e.g., βmax stock price in this time window,β updated as new prices stream in).
- Bioinformatics: Range queries over genomic sequence data.
9. Implementation (C++17)
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
// A Segment Tree for RANGE SUM queries with POINT updates.
// (For range min/max, just change the combine function and identity value.)
class SegmentTree {
private:
std::vector<long long> tree;
int n;
// Build the tree recursively. node covers array range [lo, hi].
void build(const std::vector<int>& arr, int node, int lo, int hi) {
if (lo == hi) {
tree[node] = arr[lo]; // leaf: directly the array value
return;
}
int mid = lo + (hi - lo) / 2;
build(arr, 2 * node + 1, lo, mid);
build(arr, 2 * node + 2, mid + 1, hi);
tree[node] = tree[2 * node + 1] + tree[2 * node + 2]; // combine children
}
// Query the sum of [qlo, qhi]. node covers [lo, hi].
long long query(int node, int lo, int hi, int qlo, int qhi) {
if (qhi < lo || hi < qlo) return 0; // completely outside β identity for sum
if (qlo <= lo && hi <= qhi) return tree[node]; // completely inside β no need to recurse further
int mid = lo + (hi - lo) / 2;
long long leftSum = query(2 * node + 1, lo, mid, qlo, qhi);
long long rightSum = query(2 * node + 2, mid + 1, hi, qlo, qhi);
return leftSum + rightSum; // partial overlap β combine both halves
}
// Point update: set arr[idx] = value. node covers [lo, hi].
void update(int node, int lo, int hi, int idx, int value) {
if (lo == hi) {
tree[node] = value; // reached the target leaf
return;
}
int mid = lo + (hi - lo) / 2;
if (idx <= mid) update(2 * node + 1, lo, mid, idx, value);
else update(2 * node + 2, mid + 1, hi, idx, value);
tree[node] = tree[2 * node + 1] + tree[2 * node + 2]; // recompute on the way back up
}
public:
SegmentTree(const std::vector<int>& arr) : n(arr.size()) {
tree.assign(4 * n, 0); // common safe-size convention: 4n covers any n
if (n > 0) build(arr, 0, 0, n - 1);
}
// Public range sum query. O(log n).
long long rangeSum(int qlo, int qhi) {
return query(0, 0, n - 1, qlo, qhi);
}
// Public point update. O(log n).
void pointUpdate(int idx, int value) {
update(0, 0, n - 1, idx, value);
}
};
// Example usage
int main() {
std::vector<int> arr = {2, 4, 5, 7, 8, 9};
SegmentTree segTree(arr);
std::cout << "Sum [1,4]: " << segTree.rangeSum(1, 4) << "\n"; // 4+5+7+8 = 24
segTree.pointUpdate(2, 10); // arr[2]: 5 -> 10
std::cout << "After update, Sum [0,5]: " << segTree.rangeSum(0, 5) << "\n"; // 2+4+10+7+8+9 = 40
std::cout << "Sum [1,4] after update: " << segTree.rangeSum(1, 4) << "\n"; // 4+10+7+8 = 29
return 0;
}
10. Code Walkthrough
treesized4 * n: This is a well-known safe upper bound for the array representation of a segment tree over n leaves, accounting for the tree not necessarily being a perfectly complete binary tree (unlike a Heap) β using2i+1/2i+2indexing can βwasteβ some slots when n isnβt a power of 2, and 4n comfortably covers the worst case.buildβs base case (lo == hi): A single-element range is a leaf β directly copy the array value, no combining needed. The recursive case builds both halves first, then combines β this bottom-up combination is what makes each nodeβs value correct by construction.queryβs three-way branch: This is the heart of the O(log n) query complexity β βcompletely outsideβ and βcompletely insideβ both terminate immediately without further recursion; only βpartial overlapβ recurses into both children. Most of the recursion treeβs nodes hit one of the two immediate-return cases, not the recursive case β which is exactly why total work stays O(log n).updateβs βrecompute on the way back upβ (tree[node] = tree[2*node+1] + tree[2*node+2]): Executed after the recursive call returns, ensuring children are already updated before the parent recomputes β this bottom-up recompute pattern mirrorsbuildβs combination step exactly.- Swapping for a different aggregate: To convert this into a range-MIN segment tree, youβd change
return 0(outside case) toreturn INT_MAX(the identity for min), and change every+combination tostd::min(...). This symmetry β just swap the combine function and identity β is what makes segment trees so flexible.
Common mistakes to watch for here:
- Using the wrong βidentityβ value for the aggregate (0 for sum is correct, but would be catastrophically wrong for min/max, where you need +β/-β respectively).
- Off-by-one errors in
midcalculation or range boundaries (qlo <= lo && hi <= qhivs.<mistakes) β segment trees are notoriously easy to get subtly wrong here. - Under-sizing the
treearray (using2ninstead of4n), causing out-of-bounds access for certain n.
11. Dry Run
Array: [2, 4, 5, 7, 8, 9]. Query rangeSum(1, 4):
Matches the section 3 walkthrough exactly:
- Node
[0,5]: partial overlap with[1,4]β recurse both children. - Node
[0,2]: partial overlap β recurse.- Node
[0,1]: partial overlap β recurse.- Node
[0,0]:[0,0]vs query[1,4]βhi(0) < qlo(1)β completely outside β return 0. - Node
[1,1]:qlo(1) <= lo(1)andhi(1) <= qhi(4)β completely inside β return 4.
- Node
- Node
[2,2]: completely inside[1,4]β return 5.
- Node
- Node
[3,5]: partial overlap β recurse.- Node
[3,4]: completely inside[1,4]β return 15. - Node
[5,5]:lo(5) > qhi(4)β completely outside β return 0.
- Node
Sum: 0 + 4 + 5 + 15 + 0 = 24. β (Manually: 4+5+7+8 = 24.)
Now pointUpdate(2, 10): Recurse down to leaf [2,2], set to 10. Recompute [0,2] = tree0,1 + tree2,2 = 16. Recompute [0,5] = tree0,2 + tree3,5 = 40. Only 2 ancestor nodes recomputed β O(log n) work, not O(n).
12. Interview Questions
Conceptual:
- Why is a Segment Treeβs range query O(log n) rather than O(n) or O(logΒ² n)?
- Compare Segment Tree vs. Fenwick Tree β when would you choose each?
- What is lazy propagation, and why is it necessary for efficient range updates?
- Why does a Segment Tree need ~4n space instead of exactly 2n?
- How would you adapt a sum Segment Tree into a min/max/GCD Segment Tree?
Coding:
- Range Sum Query - Mutable (LeetCode 307) β the canonical Segment Tree problem.
- Range Minimum/Maximum Query with point updates.
- Count of Smaller Numbers After Self (using a Segment Tree over value ranks).
- Implement lazy propagation for range-update, range-sum-query.
- Falling Squares (interval max-height queries).
Follow-ups / interviewer traps:
- βCan you support range updates without lazy propagation, and whatβs the complexity cost?β (naive per-element update: O(range Γ log n) β expects you to identify this as too slow for large ranges, and know lazy propagation as the fix)
- βHow would this differ if the array itself could change size (insertions/deletions), not just values?β (a plain segment tree assumes fixed size; dynamic sizing needs a different structure entirely, like a balanced-tree-based segment tree)
13. Practice Problems
Easy
- Range Sum Query - Immutable (LeetCode 303) β simpler prefix-sum suffices here, but good grounding.
Medium
- Range Sum Query - Mutable (LeetCode 307)
- Count of Range Sum (LeetCode 327)
Hard
- Falling Squares (LeetCode 699)
- Count of Smaller Numbers After Self (LeetCode 315)
- The Skyline Problem (LeetCode 218) β often solved with a Segment Tree variant
Also recommended: Codeforces problems tagged data structures + segment tree (1500-2000 rating range), GeeksforGeeks βSegment Treeβ practice set.
14. Common Mistakes
- Using the wrong identity value for the aggregate operation (0 for sum β correct identity for min/max).
- Off-by-one errors in range boundaries and midpoint calculations β the single most common source of Segment Tree bugs.
- Under-allocating the tree array β always use the safe 4n convention unless youβve proven a tighter bound is safe for your specific n.
- Forgetting to recompute ancestors after an update β or recomputing in the wrong order (must happen bottom-up, after children are already updated).
- Reaching for a Segment Tree when a simpler Fenwick Tree (or even a plain prefix sum, if there are no updates) would suffice β added complexity should be justified by an actual need for range updates or non-sum aggregates.
15. Summary
Key takeaways:
- A Segment Tree stores range aggregates hierarchically, enabling O(log n) range queries and updates simultaneously β a combination plain arrays and prefix sums cannot achieve together.
- The query algorithmβs βstop at full containment, recurse only on partial overlapβ logic is what bounds total work to O(log n).
- Lazy propagation extends the structure to efficient range (not just point) updates.
- Itβs flexible for any associative operation with an identity β sum, min, max, GCD, XOR, or custom combiners.
Complexity recap:
| Operation | Time | Space |
|---|---|---|
| Build | O(n) | O(n) |
| Range Query | O(log n) | O(log n) |
| Point Update | O(log n) | O(log n) |
| Range Update (lazy) | O(log n) | O(n) extra |
Decision guideline: Reach for a Segment Tree when you need both range queries and updates on an array, especially for non-sum aggregates (min, max, GCD) or when you anticipate needing range (not just point) updates via lazy propagation. If you only need prefix sums with point updates, the simpler and lighter-weight Fenwick Tree (next chapter) is usually the better choice.
Next chapter: 15_fenwick_tree.md
Chapter 15: Fenwick Tree (Binary Indexed Tree, BIT)
Study time: ~5-6 hours | Prerequisite: Arrays, Bit Manipulation basics, Segment Tree (helpful for contrast) | Difficulty: Advanced
1. Introduction
Definition: A Fenwick Tree (also called a Binary Indexed Tree, or BIT) is a compact array-based structure that supports prefix sum queries and point updates, both in O(log n), using clever bit manipulation instead of an explicit tree of pointers or a 4x-oversized array.
Purpose: To solve the exact same core problem as a Segment Tree β efficient range queries with efficient updates β but with a simpler implementation and roughly half the memory, specifically for prefix-sum-style (and other simply invertible) aggregate operations.
Real-world analogy: Think of a Fenwick Tree as a very well-organized set of βrunning subtotalβ receipts, where each receipt only needs to be updated in a small, precisely chosen set of places when one purchase changes β rather than re-adding everything from the start, or (like a Segment Tree) walking an explicit tree structure. The βwhich placesβ is determined entirely by the binary representation of the index β a clever mathematical shortcut that replaces tree pointers with arithmetic.
Motivation: A Segment Tree solves the βrange query + updateβ problem generally and flexibly, but for the common special case of prefix sums, its generality costs extra memory (4n) and more code. A Fenwick Tree achieves the same asymptotic complexity (O(log n) query and update) with a single flat array of size n+1 and two simple bit-manipulation formulas β no recursion, no explicit tree structure required (though it can be understood as an implicit tree).
History: Introduced by Peter Fenwick in a 1994 paper on βa new data structure for cumulative frequency tables,β originally motivated by data compression algorithms needing fast cumulative frequency counts.
2. Why Do We Need It?
Problem it solves: Prefix sum queries and point updates, both in O(log n), with minimal memory and implementation complexity.
Why previous structures are insufficient:
- Prefix sum array: O(1) query, but O(n) update (must shift every subsequent prefix sum).
- Plain array: O(1) update, but O(n) query (must sum a whole prefix each time).
- Segment Tree: achieves the same O(log n) for both, but with ~4x the memory and a more involved recursive implementation β overkill when you only need sums (not arbitrary min/max/custom aggregates) and donβt need lazy-propagation-style range updates.
Trade-offs:
- You gain O(log n) query/update with a tiny memory footprint (a single array of size n+1) and remarkably short, iterative (no recursion needed) code.
- You lose the Segment Treeβs flexibility β a plain Fenwick Tree naturally handles only aggregates with an efficient inverse operation (sumβs inverse is subtraction β this is what makes range-sum-via-two-prefix-sums work). Min/max, notably, do NOT have a usable inverse this way, so a standard Fenwick Tree cannot efficiently support range min/max queries the way a Segment Tree can.
3. Internal Working
The key trick: every indexβs βresponsibility rangeβ is determined by its lowest set bit.
For array size n=8 (1-indexed, which is the standard convention for Fenwick Trees β this avoids awkward edge cases at index 0):
Index (binary): 1(0001) 2(0010) 3(0011) 4(0100) 5(0101) 6(0110) 7(0111) 8(1000)
Responsible for: [1] [1,2] [3] [1,2,3,4] [5] [5,6] [7] [1..8]
Each Fenwick array slot tree[i] stores the sum of a specific range ending at i, whose length is determined by iβs lowest set bit (the rightmost 1 in its binary representation). For example, tree[4] (binary 100, lowest set bit = 4) covers the sum of elements [1,2,3,4] β a range of length 4. tree[6] (binary 110, lowest set bit = 2) covers [5,6] β a range of length 2.
Update (adding delta to position i): move to the next index that also needs updating, by repeatedly adding the lowest set bit:
i = i + (i & (-i))
Prefix sum query up to index i: move to the previous relevant index by repeatedly removing the lowest set bit:
i = i - (i & (-i))
Example β update index 3 by +5 (n=8):
Start i=3 (binary 011). Update tree[3].
i += (3 & -3) = 3 + 1 = 4 (binary 100). Update tree[4].
i += (4 & -4) = 4 + 4 = 8 (binary 1000). Update tree[8].
i += (8 & -8) = 8 + 8 = 16 > n=8, STOP.
Updated: tree[3], tree[4], tree[8] β exactly the 3 nodes whose "responsibility range" includes index 3.
Example β prefix sum query up to index 6 (binary 110):
Start i=6 (binary 110). Add tree[6] (covers [5,6]).
i -= (6 & -6) = 6 - 2 = 4 (binary 100). Add tree[4] (covers [1,2,3,4]).
i -= (4 & -4) = 4 - 4 = 0. STOP (i=0 means done).
Total = tree[6] + tree[4] = sum([5,6]) + sum([1,2,3,4]) = sum([1..6]) β
This is the entire mechanism β no explicit tree, no pointers, just two lines of bit arithmetic that implicitly navigate an underlying tree structure encoded in the binary representation of indices.
4. Operations
Update(index, delta):
- Starting at
index(1-indexed), repeatedly adddeltatotree[index], then move toindex += index & (-index), untilindexexceeds array size n. - O(log n) β each step strictly increases
index, and there are at most O(log n) such steps (the number of bits in n).
Prefix Sum Query(index):
- Starting at
index, repeatedly addtree[index]to a running total, then move toindex -= index & (-index), untilindexreaches 0. - O(log n) β symmetric reasoning to Update.
Range Sum Query(L, R):
- Computed as
prefixSum(R) - prefixSum(L-1)β this is exactly why sum (which has a clean inverse, subtraction) works so elegantly with a Fenwick Tree, while min/max (no clean inverse) do not.
Point Update (set, not just add):
- To set index
ito a new valuev(rather than adding a delta), first query the current value ati(viaprefixSum(i) - prefixSum(i-1)), computedelta = v - currentValue, then callUpdate(i, delta).
Build from an initial array:
- Simplest approach: start with all zeros, then call
Update(i, arr[i])for eachiβ O(n log n) total. A more advanced O(n) construction exists but is rarely necessary in practice.
5. Time & Space Complexity
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Update (point) | O(log n) | O(1) extra |
| Prefix Sum Query | O(log n) | O(1) extra |
| Range Sum Query | O(log n) | O(1) extra |
| Build from array (naive) | O(n log n) | O(n) |
| Overall storage | β | O(n) β just one array, no 4x overhead |
Why these hold:
- Both Update and Query are O(log n) because each step of
i += i & (-i)(or the subtractive equivalent) strictly changesiβs binary representation in a way that can happen at most O(log n) times before exceeding n (or reaching 0) β directly tied to nβs number of bits. - Storage is exactly O(n) β a single array of size n+1 β versus the Segment Treeβs conventional 4n, a meaningful practical memory saving at scale.
6. Advantages
- Minimal memory: a single array of size n+1, versus a Segment Treeβs ~4n.
- Simple, short, iterative code β no recursion, no explicit tree nodes/pointers.
- O(log n) for both prefix-sum-style queries and point updates.
- Easy to reason about once the bit-manipulation trick clicks (though that initial βclickβ can take real study time).
7. Disadvantages
- Limited to operations with a usable inverse (sum/subtraction is the classic case) β cannot directly support range min/max/GCD the way a Segment Tree can (some advanced variants exist for min/max with extra tricks, but theyβre considerably more complex and lose some of the simplicity that makes Fenwick Trees appealing in the first place).
- Less intuitive at first glance than a Segment Tree β the bit-manipulation logic, while elegant once understood, isnβt as immediately visual as an explicit tree.
- Range updates (updating every element in a range) require an extra trick (a second Fenwick Tree, or a βdifference arrayβ technique) to remain O(log n) β not as naturally supported as a Segment Tree with lazy propagation.
8. Real-World Applications
- Competitive Programming: The default go-to structure for βpoint update, prefix/range sum queryβ problems β even more common than Segment Trees due to its simplicity, whenever a Segment Treeβs extra flexibility isnβt needed.
- Data Compression: Fenwickβs original motivation β maintaining cumulative frequency tables efficiently for algorithms like arithmetic coding.
- Databases/Analytics: Efficient running-total/cumulative-statistics computation over frequently-updated data.
- Inversion Counting: Counting the number of βinversionsβ in a sequence (a classic algorithmic subproblem in sorting analysis and computational biology) is efficiently solved using a Fenwick Tree over ranks.
- Order Statistics: Answering βhow many elements inserted so far are less than Xβ efficiently, which is foundational to some streaming/online algorithm designs.
9. Implementation (C++17)
#include <iostream>
#include <vector>
// A Fenwick Tree (Binary Indexed Tree) supporting point updates and prefix sum queries.
// Uses 1-INDEXED internally (the standard convention) to avoid the (index & -index)
// trick breaking down at index 0.
class FenwickTree {
private:
std::vector<long long> tree;
int n;
public:
// Construct a Fenwick Tree of size n, all zeros initially.
FenwickTree(int size) : n(size), tree(size + 1, 0) {}
// Add `delta` to the element at 1-indexed position `i`. O(log n).
void update(int i, long long delta) {
for (; i <= n; i += i & (-i)) {
tree[i] += delta;
}
}
// Sum of elements [1, i] (1-indexed prefix sum). O(log n).
long long prefixSum(int i) const {
long long sum = 0;
for (; i > 0; i -= i & (-i)) {
sum += tree[i];
}
return sum;
}
// Sum of elements [l, r] (1-indexed, inclusive). O(log n).
long long rangeSum(int l, int r) const {
return prefixSum(r) - prefixSum(l - 1); // the "inverse" trick sum uniquely allows
}
// Build from an existing 0-indexed array. O(n log n) via repeated point updates.
static FenwickTree buildFromArray(const std::vector<int>& arr) {
FenwickTree ft(arr.size());
for (size_t i = 0; i < arr.size(); ++i) {
ft.update(static_cast<int>(i) + 1, arr[i]); // convert to 1-indexed
}
return ft;
}
};
// Example usage
int main() {
std::vector<int> arr = {2, 4, 5, 7, 8, 9}; // 0-indexed input
FenwickTree ft = FenwickTree::buildFromArray(arr);
std::cout << "Sum [1,4] (0-indexed, i.e. 1-indexed [2,5]): "
<< ft.rangeSum(2, 5) << "\n"; // 4+5+7+8 = 24 (matches Segment Tree chapter's example)
// Point update: arr[2] (0-indexed) changes from 5 to 10 β delta = +5, at 1-indexed position 3
ft.update(3, 5);
std::cout << "After update, Sum [1,6] (all elements): " << ft.prefixSum(6) << "\n"; // 40
std::cout << "Sum [1,4] (0-indexed [2,5]) after update: " << ft.rangeSum(2, 5) << "\n"; // 29
return 0;
}
10. Code Walkthrough
- 1-indexing throughout: This is a deliberate, standard convention β the
i & (-i)trick relies oniβs binary representation, and index 0 has no set bits at all, which would break the loop termination logic (i -= i & (-i)would never change from 0). Starting at 1 avoids this entirely. i & (-i)(isolating the lowest set bit): In twoβs-complement representation,-iis the bitwise NOT ofiplus 1; ANDingiwith-iisolates exactly the lowest set bit. This one expression is the entire βmagicβ behind bothupdateandprefixSumβ no explicit tree traversal is needed because this arithmetic implicitly walks the tree structure encoded in the binary index.updateβs loop (i += i & (-i)): Moves to the next index whose βresponsibility rangeβ also covers the updated position β visually, this is climbing βupβ the implicit tree toward larger ranges.prefixSumβs loop (i -= i & (-i)): Moves to the previous index needed to complete the prefix sum β visually, this is descending through the implicit tree, picking up pre-computed range sums along the way.rangeSumvia two prefix sums subtracted: This single line is why Fenwick Trees are naturally suited to sum (and other operations with a clean inverse) βsum(rangeL,R) = prefixSum(R) - prefixSum(L-1)only works because subtraction correctly βundoesβ addition. Min/max have no equivalent trick (minhas no inverse operation that lets you βremoveβ a valueβs contribution this way).
Common mistakes to watch for here:
- Using 0-indexing without adjustment β breaks the
i & (-i)logic at index 0. - Confusing
update(adds a delta) with a naive βsetβ operation β remember you must compute the delta yourself if you want to set a value rather than add to it. - Forgetting the
-1inrangeSum(l, r) = prefixSum(r) - prefixSum(l-1)β an extremely common off-by-one.
11. Dry Run
Build from [2, 4, 5, 7, 8, 9] (0-indexed), converting to 1-indexed updates: update(1,2), update(2,4), update(3,5), update(4,7), update(5,8), update(6,9).
Trace update(3, 5):
i=3 (011): tree[3] += 5
i = 3 + (3 & -3) = 3 + 1 = 4 (100): tree[4] += 5
i = 4 + (4 & -4) = 4 + 4 = 8 β 8 > n=6, STOP
Only tree[3] and tree[4] touched β O(log n) = O(3) steps for n=6, matching the bound.
Trace prefixSum(5) (sum of elements [1..5], which in original terms is [2,4,5,7,8] = 26):
i=5 (101): sum += tree[5]
i = 5 - (5 & -5) = 5 - 1 = 4 (100): sum += tree[4]
i = 4 - (4 & -4) = 4 - 4 = 0, STOP
Result: tree[5] + tree[4]
After all the builds above, tree[4] holds the cumulative contribution for range [1,4] = 2+4+5+7=18, and tree[5] holds just position 5βs value = 8 (since 5βs binary is 101, lowest set bit =1, meaning itβs responsible for a range of length 1 β just itself). Sum = 18 + 8 = 26. β Matches manual sum of [2,4,5,7,8].
12. Interview Questions
Conceptual:
- Explain how
i & (-i)isolates the lowest set bit, and why thatβs the key to Fenwick Tree operations. - Why must Fenwick Trees be 1-indexed?
- Compare Fenwick Tree vs. Segment Tree β memory, flexibility, and implementation complexity trade-offs.
- Why canβt a standard Fenwick Tree efficiently support range MIN/MAX queries the way it supports range SUM?
- How would you use a Fenwick Tree to count inversions in an array?
Coding:
- Range Sum Query - Mutable (LeetCode 307) β solvable with either Segment Tree or Fenwick Tree; implement with Fenwick Tree here for contrast.
- Count of Smaller Numbers After Self (LeetCode 315) β classic Fenwick-over-ranks application.
- Count Inversions in an array.
- Range Addition (using a Fenwick Tree for the βdifference arrayβ range-update trick).
Follow-ups / interviewer traps:
- βCan you extend your Fenwick Tree to support range updates as well as range queries?β (expects the βtwo Fenwick Treesβ or difference-array trick β noticeably more involved than the point-update version)
- βWhy would you choose a Fenwick Tree over a Segment Tree here?β (tests whether they understand itβs about memory/simplicity trade-off when only sum-like aggregates are needed, not raw speed β both are O(log n))
13. Practice Problems
Easy
- Range Sum Query - Immutable (LeetCode 303) β good baseline before adding mutability.
Medium
- Range Sum Query - Mutable (LeetCode 307)
- Count of Range Sum (LeetCode 327)
Hard
- Count of Smaller Numbers After Self (LeetCode 315)
- Count of Range Sum (LeetCode 327, harder variant)
- Create Sorted Array through Instructions (LeetCode 1649)
Also recommended: Codeforces problems tagged data structures + fenwick/bit (1400-1900 rating range), GeeksforGeeks βBinary Indexed Treeβ practice set.
14. Common Mistakes
- Forgetting 1-indexing, silently breaking the bit-manipulation logic at index 0.
- Off-by-one in
rangeSum(l, r) = prefixSum(r) - prefixSum(l-1)β a very common bug. - Confusing
update(add a delta) with asetoperation β must compute and pass the delta, not the new absolute value directly. - Assuming Fenwick Trees can trivially handle min/max range queries β they cannot, without significantly more complex extensions, precisely because min/max lack a usable inverse operation.
- Reaching for a Fenwick Tree when the array never needs updates β a simple prefix sum array is simpler and just as fast (O(1) query) in that case.
15. Summary
Key takeaways:
- A Fenwick Tree achieves the same O(log n) query/update as a Segment Tree, but with a single flat array and elegant bit-manipulation instead of an explicit tree β at the cost of only working cleanly for aggregates with a usable inverse (sum being the classic case).
i & (-i)isolates the lowest set bit β the single arithmetic trick underlying bothupdateandprefixSum.- 1-indexing is mandatory, not optional, for the bit-manipulation logic to work correctly.
Complexity recap:
| Operation | Time | Space |
|---|---|---|
| Update | O(log n) | O(1) extra |
| Prefix Sum Query | O(log n) | O(1) extra |
| Range Sum Query | O(log n) | O(1) extra |
| Overall Storage | β | O(n) |
Decision guideline: Choose a Fenwick Tree when your problem is a prefix-sum/frequency-count-style range query with point updates β itβs simpler and lighter than a Segment Tree for this common case. Choose a Segment Tree instead when you need range min/max/GCD, custom non-invertible aggregates, or lazy-propagation-style range updates.
Next chapter: 16_disjoint_set_union.md
Chapter 16: Disjoint Set Union (Union-Find)
Study time: ~5-6 hours | Prerequisite: Arrays, basic amortized analysis | Difficulty: Intermediate-Advanced
1. Introduction
Definition: A Disjoint Set Union (DSU), also called Union-Find, is a data structure that maintains a collection of disjoint (non-overlapping) sets and supports two core operations extremely efficiently: Find (which set does element X belong to?) and Union (merge the sets containing X and Y).
Purpose: To answer βare these two elements connected/in the same group?β and to merge groups together, both in near-constant amortized time β dramatically faster than re-running a full graph traversal (BFS/DFS) every time connectivity needs checking.
Real-world analogy: Think of merging companies. Each company has a CEO (the βrepresentativeβ of that set). When two companies merge, one CEO becomes the overall boss, and everyone can trace up their reporting chain to find out who their ultimate boss is now. βAre Alice and Bob in the same company?β is answered by tracing both up to their ultimate boss and checking if itβs the same person β you donβt need to know every intermediate connection, just whoβs at the top.
Motivation: Graph connectivity questions (βare u and v connected?β, βdoes adding this edge create a cycle?β) could be answered by re-running BFS/DFS each time β O(V+E) per query. When you need to answer many such queries as a graph evolves (edges added incrementally), DSU answers each one in near O(1) amortized instead, after some efficient bookkeeping.
History: The core idea dates to the 1960s; the two critical optimizations β union by rank and path compression β were analyzed and popularized in the 1970s-80s, with the resulting near-O(1) amortized bound (formally O(Ξ±(n)), where Ξ± is the inverse Ackermann function) proven by Tarjan.
2. Why Do We Need It?
Problem it solves: Efficiently tracking and merging groups of connected elements, and answering βare these two in the same group?β repeatedly, as connections are added over time.
Why previous structures are insufficient:
- Re-running BFS/DFS per query: correct, but O(V+E) every single time β far too slow if you need to answer many connectivity queries, especially as edges keep being added.
- Hash Map tracking group IDs directly: naive approaches (relabeling every member of a merged group) cost O(size of group) per union β can degrade to O(n) per merge in the worst case if done carelessly.
Trade-offs:
- You gain near-O(1) amortized Find and Union β a massive improvement enabling algorithms like Kruskalβs MST (Chapter 11) to work efficiently.
- You pay for it with a structure that only answers βsame group?β β it cannot enumerate a groupβs members efficiently, tell you the path between two connected elements, or handle disconnection (removing an edge/splitting a group) at all; DSU is fundamentally a βmerge-onlyβ structure.
3. Internal Working
Representation: an array parent[], where parent[i] points to iβs parent in an implicit tree; a root points to itself (parent[root] == root).
Initial state (5 elements, all separate):
parent = [0, 1, 2, 3, 4] (everyone is their own root β 5 separate sets)
Union(0, 1): make one root point to the other:
parent = [1, 1, 2, 3, 4] (0's root is now 1; set {0,1} formed)
Union(2, 3):
parent = [1, 1, 3, 3, 4] (set {2,3} formed)
Find(0): follow parent pointers until reaching a self-pointing root: 0 β 1 (1 points to itself) β root is 1.
Without optimization, repeated unions can create long chains (a βlinked-listβ worst case), making Find degrade to O(n):
parent = [1, 2, 3, 4, 4] (0β1β2β3β4, a long chain β Find(0) takes 4 steps)
Optimization 1 β Path Compression: during Find, make every node on the path point directly to the root, flattening the tree for all future queries:
Before Find(0): 0β1β2β3β4
After Find(0) with path compression: 0β4, 1β4, 2β4, 3β4 (all flattened directly to root)
Optimization 2 β Union by Rank (or Size): when merging two sets, always attach the smaller treeβs root under the larger treeβs root β this prevents chains from forming in the first place, keeping trees shallow.
Union by rank example: merging a tree of rank 3 with a tree of rank 1 β
attach the rank-1 tree's root under the rank-3 tree's root (not the other way around),
since attaching the bigger tree under the smaller one would needlessly increase overall height.
Together, path compression + union by rank give the famous near-O(1) amortized bound β proven to be O(Ξ±(n)), where Ξ± (inverse Ackermann function) grows so slowly that itβs less than 5 for any n you could ever practically encounter, making it βeffectively constantβ in every real-world sense.
4. Operations
MakeSet(x):
- Initialize x as its own set:
parent[x] = x,rank[x] = 0. - O(1).
Find(x):
- Follow
parentpointers until reaching a node that is its own parent (the root). - With path compression: as the recursion unwinds, set every visited nodeβs parent directly to the root β flattening future lookups.
- Amortized O(Ξ±(n)) β O(1) with both optimizations; O(log n) with only union-by-rank; O(n) worst case with neither.
Union(x, y):
- Find the roots of x and y. If theyβre already the same root, theyβre already in the same set β do nothing (this check is also how you detect βwould this edge create a cycleβ in Kruskalβs algorithm).
- Otherwise, attach the smaller-rank root under the larger-rank root (union by rank); if ranks are equal, attach either one and increment the resulting rootβs rank by 1.
- Amortized O(Ξ±(n)) β O(1) with both optimizations.
Connected(x, y):
- Simply
Find(x) == Find(y). Same complexity as Find.
What DSU cannot do: split a set apart (undo a union), efficiently enumerate all members of a given set (would require a separate auxiliary structure), or answer βwhat is the path between x and yβ (only βare they connected,β not βhowβ).
5. Time & Space Complexity
| Operation | With Path Compression + Union by Rank | With Only One Optimization | With Neither | Space |
|---|---|---|---|---|
| Find | O(Ξ±(n)) β O(1) amortized | O(log n) | O(n) worst case | O(n) |
| Union | O(Ξ±(n)) β O(1) amortized | O(log n) | O(n) worst case | O(1) extra |
| n operations total | O(nΒ·Ξ±(n)) β O(n) | O(n log n) | O(nΒ²) worst case | O(n) |
Why these hold:
- Without any optimization, repeated unions can form a degenerate chain (as shown in section 3), making
FindO(n) in the worst case β no better than a plain linked list traversal. - Union by rank alone guarantees tree height stays O(log n), since attaching the smaller tree under the larger one means a treeβs height can only increase when merging with an equal-or-larger tree, which (by an argument similar to the dynamic arrayβs amortized doubling) can only happen O(log n) times before a treeβs size exceeds n.
- Path compression alone also provides a strong amortized bound (O(log n) amortized) by flattening paths as theyβre traversed β repeated
Findcalls on the same elements get progressively cheaper. - Combined, the two optimizations interact synergistically, producing the famous O(Ξ±(n)) bound (Tarjanβs result) β practically indistinguishable from O(1) for any n that will ever be encountered in practice (Ξ±(n) β€ 4 for n up to numbers vastly larger than the number of atoms in the observable universe).
6. Advantages
- Near-O(1) amortized Find/Union β among the fastest possible structures for the specific βtrack and merge groupsβ problem.
- Extremely simple to implement (a single array, two short functions) relative to its algorithmic power.
- Essential building block for several classic graph algorithms (Kruskalβs MST, cycle detection in undirected graphs, connected components tracking).
7. Disadvantages
- Cannot undo a union (no efficient βsplitβ operation) β fundamentally a merge-only structure.
- Cannot enumerate a setβs members efficiently without an auxiliary structure (e.g., a separate list per root, maintained alongside).
- Doesnβt store or reveal why two elements are connected (no path information) β only whether they are.
- The near-O(1) bound requires both optimizations to be implemented correctly; naive implementations can silently degrade to much worse performance.
8. Real-World Applications
- Kruskalβs MST algorithm (Chapter 11): DSU is the mechanism for efficiently checking βwould adding this edge create a cycle?β
- Network Connectivity: Determining if two computers/nodes are on the same network segment, as connections are added incrementally.
- Image Processing: Connected-component labeling (grouping adjacent pixels of the same color/region) can be implemented efficiently with DSU.
- Social Networks: βAre these two people in the same friend group/community?β as friendships (edges) are added over time.
- Percolation Theory / Physics Simulations: Modeling whether a fluid can βpercolateβ through a randomly-connected grid β a classic DSU application in computational physics.
- Compiler Design: Some register-allocation and variable-aliasing analyses use union-find-like structures to track equivalence classes.
- Games: Puzzle games involving connected regions (e.g., minesweeper-style flood detection, some maze-generation algorithms like Kruskalβs-based random maze generation).
9. Implementation (C++17)
#include <iostream>
#include <vector>
#include <numeric>
class DisjointSetUnion {
private:
std::vector<int> parent;
std::vector<int> rank_; // "rank_" to avoid shadowing std::rank
int numSets; // tracks how many distinct sets currently exist
public:
DisjointSetUnion(int n) : parent(n), rank_(n, 0), numSets(n) {
std::iota(parent.begin(), parent.end(), 0); // parent[i] = i initially
}
// Find with PATH COMPRESSION. Amortized O(alpha(n)).
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]); // recursively find the root, then attach x DIRECTLY to it
}
return parent[x];
}
// Union with UNION BY RANK. Amortized O(alpha(n)). Returns false if x,y already connected.
bool unite(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) return false; // already in the same set β union would be a no-op (or "creates a cycle" in MST context)
// Attach the smaller-rank tree under the larger-rank tree's root.
if (rank_[rootX] < rank_[rootY]) {
parent[rootX] = rootY;
} else if (rank_[rootX] > rank_[rootY]) {
parent[rootY] = rootX;
} else {
parent[rootY] = rootX; // equal ranks: pick either as new root
rank_[rootX]++; // and increment the resulting root's rank
}
numSets--;
return true;
}
bool connected(int x, int y) {
return find(x) == find(y);
}
int countSets() const { return numSets; }
};
// Example usage
int main() {
DisjointSetUnion dsu(6); // elements 0..5, initially 6 separate sets
dsu.unite(0, 1);
dsu.unite(1, 2);
dsu.unite(3, 4);
std::cout << "connected(0,2)? " << dsu.connected(0, 2) << "\n"; // 1 (true) β 0-1-2 merged
std::cout << "connected(0,3)? " << dsu.connected(0, 3) << "\n"; // 0 (false) β different groups
std::cout << "Number of sets: " << dsu.countSets() << "\n"; // 3: {0,1,2}, {3,4}, {5}
dsu.unite(2, 3); // merges {0,1,2} and {3,4} into one group
std::cout << "connected(0,4)? " << dsu.connected(0, 4) << "\n"; // 1 (true) now
std::cout << "Number of sets: " << dsu.countSets() << "\n"; // 2: {0,1,2,3,4}, {5}
return 0;
}
10. Code Walkthrough
parentinitialized viastd::iota: every element starts as its own root β n separate singleton sets, matching the βeveryone is their own bossβ starting state from section 3.findβs recursive path compression:parent[x] = find(parent[x])first recursively finds the true root, then reassignsxβs parent directly to that root as the recursion unwinds β this is what flattens the tree over successive calls. The very nextfind(x)call will take O(1) β a direct hop.uniteβs rank comparison: The three-way branch (<,>,==) implements union-by-rank exactly as described in section 3 β the smaller-rank tree always attaches under the larger, and rank only increases when two equal-rank trees merge (this specific condition is what keeps the O(log n) bound tight even without path compression).rootX == rootYearly return: This single check is doing double duty β in a general DSU context it means βno-op, already connectedβ; in Kruskalβs MST context (Chapter 11), this exact same check is what identifies βthis edge would create a cycle, skip it.βnumSetsbookkeeping: Decremented only on a successful merge (not a no-op union) β this letscountSets()answer βhow many connected components existβ in O(1), a common and useful auxiliary capability.
Common mistakes to watch for here:
- Forgetting path compression (
parent[x] = find(parent[x])instead of justreturn find(parent[x])without reassignment) β the return is easy to get right, but forgetting the reassignment silently loses all the flattening benefit. - Always attaching by a fixed convention (e.g., βsmaller index always becomes the new rootβ) instead of by rank/size β this can recreate long chains and lose the balance guarantee.
- Not checking
rootX == rootYbefore merging β attempting to βunionβ two elements already in the same set should be a safe no-op, not cause incorrect rank bookkeeping.
11. Dry Run
6 elements. Operations: unite(0,1), unite(1,2), unite(3,4), find(0), unite(2,3)
| Step | Action | parent[] | rank_[] | Notes |
|---|---|---|---|---|
| init | β | [0,1,2,3,4,5] | [0,0,0,0,0,0] | 6 separate sets |
| unite(0,1) | find(0)=0, find(1)=1, ranks equal | [1,1,2,3,4,5] | [0,1,0,0,0,0] | 1 becomes root, rank[1]++ |
| unite(1,2) | find(1)=1 (rank1), find(2)=2(rank0) β 2 attaches under 1 | [1,1,1,3,4,5] | [0,1,0,0,0,0] | rank[1] stays 1 (merging with a STRICTLY smaller rank doesnβt increment) |
| unite(3,4) | find(3)=3, find(4)=4, ranks equal | [1,1,1,4,4,5] | [0,1,0,0,1,0] | 4 becomes root, rank[4]++ |
| find(0) | 0β1 (root, since parent[1]=1) β path compression sets parent[0]=1 directly (already direct here, minimal effect this time) | [1,1,1,4,4,5] | unchanged | root = 1 |
| unite(2,3) | find(2)=1 (rank1), find(3)=4(rank1) β ranks EQUAL β 4 attaches under 1, rank[1]++ | [1,1,1,4,1,5] | [0,2,0,0,1,0] | now {0,1,2,3,4} all connected, root=1 |
Final: connected(0,4) β find(0)=1, find(4): parent[4]=1 β root 1. Match! True. β
12. Interview Questions
Conceptual:
- Explain path compression and union by rank β why does combining both give a near-O(1) bound?
- Why canβt DSU efficiently βundoβ a union (split a set back apart)?
- How does DSU detect a cycle when building an MST with Kruskalβs algorithm?
- What is the inverse Ackermann function, and why is O(Ξ±(n)) considered βeffectively constantβ?
- Compare using DSU vs. running BFS/DFS repeatedly for connectivity queries on a graph with incrementally added edges.
Coding:
- Number of Provinces / Number of Connected Components in an Undirected Graph.
- Redundant Connection β find the edge that creates a cycle.
- Accounts Merge β group accounts by shared emails using DSU.
- Number of Islands II β dynamic connectivity as land is added over time.
- Implement Kruskalβs MST using your own DSU (ties back to Chapter 11).
Follow-ups / interviewer traps:
- βWhat if you need to support removing an edge/disconnecting elements β does DSU still work?β (no β DSU fundamentally doesnβt support efficient splitting; a different structure or a full graph rebuild would be needed)
- βCan you track the SIZE of each set efficiently, not just connectivity?β (yes β maintain a size array alongside, updated during union, very similar to rank)
- βWhy not just always attach by array index instead of rank?β (tests whether they understand this can recreate long chains, losing the balance guarantee entirely)
13. Practice Problems
Easy
- Number of Provinces (LeetCode 547)
- Find if Path Exists in Graph (LeetCode 1971)
Medium
- Redundant Connection (LeetCode 684)
- Accounts Merge (LeetCode 721)
- Number of Operations to Make Network Connected (LeetCode 1319)
- Graph Valid Tree (LeetCode 261)
Hard
- Number of Islands II (LeetCode 305)
- Regions Cut By Slashes (LeetCode 959)
- Minimize Malware Spread (LeetCode 924)
Also recommended: GeeksforGeeks βUnion-Find/Disjoint Setβ practice set, Codeforces problems tagged dsu (1300-1800 rating range).
14. Common Mistakes
- Forgetting path compression β a functionally correct but performance-degraded DSU.
- Attaching roots by a fixed rule (always attach b under a) instead of by rank/size β can silently recreate chains and lose the balance guarantee.
- Not checking for βalready connectedβ before merging in cycle-detection contexts β this check IS the cycle detector; skipping it breaks Kruskalβs MST correctness.
- Confusing rank with actual tree size β rank is an upper-bound approximation of height, not a literal count of elements (a βunion by sizeβ variant exists too, tracking actual element counts, and is equally valid).
- Assuming DSU can answer βwhat is the connecting pathβ β it can only answer βare they connected,β never βhow.β
15. Summary
Key takeaways:
- DSU tracks disjoint groups and merges them, with
FindandUnionboth running in near-O(1) amortized time when combining path compression and union by rank. - The
rootX == rootYcheck inUnionis doing double duty as both βno-op detectionβ and β in graph algorithms β βcycle detection.β - DSU is a merge-only structure: no splitting, no path/route information, no efficient member enumeration without extra bookkeeping.
- Itβs the essential engine behind Kruskalβs MST and any βtrack connectivity as edges are added incrementallyβ problem.
Complexity recap:
| Operation | Time (with both optimizations) |
|---|---|
| Find | O(Ξ±(n)) β O(1) amortized |
| Union | O(Ξ±(n)) β O(1) amortized |
| Connected | O(Ξ±(n)) β O(1) amortized |
Decision guideline: Reach for DSU whenever you need to repeatedly answer βare these connected?β or merge groups as a graph/relation grows incrementally β especially for cycle detection (Kruskalβs) and connected-component tracking. If you need to remove connections or trace the actual path between elements, DSU is the wrong tool β use a different graph representation with BFS/DFS instead.
Next chapter: 17_skip_list.md (or say the word for Bloom Filter / the LRU Cache capstone instead)
Chapter 17: Skip List
Study time: ~5-6 hours | Prerequisite: Linked Lists, probability basics | Difficulty: Advanced
1. Introduction
Definition: A Skip List is a linked-list-based structure augmented with multiple βlevelsβ of shortcut pointers, where higher levels skip over more elements. Each element is randomly assigned a βheightβ (how many levels it appears in), and this randomness statistically guarantees O(log n) search, insert, and delete β without the explicit rotation logic an AVL Tree needs.
Purpose: To achieve BST-like O(log n) average performance using a much simpler, linked-list-based implementation, with the added benefit of being naturally suited to concurrent (multi-threaded) implementations, where balancing rotations in a tree are notoriously hard to make thread-safe.
Real-world analogy: Think of an express-and-local subway system layered over a single street. The βlocal trackβ (bottom level) stops at every single station β a plain linked list, O(n) to traverse. An βexpress trackβ (a higher level) skips most stations, stopping only at major hubs. A βsuper-expressβ (an even higher level) stops only at the very biggest hubs. To get from station A to station Z, you ride the super-express as far as you can, then drop to the express, then to local for the final stretch β dramatically fewer stops overall than riding local the whole way.
Motivation: AVL/Red-Black Trees guarantee O(log n) via careful, deterministic rebalancing (rotations) β powerful, but intricate to implement correctly, and awkward to make safely concurrent (a rotation can touch several nodes at once, complicating fine-grained locking). A Skip List achieves the same expected O(log n) using randomness instead of deterministic balancing β no rotations at all, and its layered structure lends itself much more naturally to lock-free/concurrent designs.
History: Invented by William Pugh in 1990, explicitly motivated as βa probabilistic alternative to balanced treesβ β the original paperβs title states this goal directly.
2. Why Do We Need It?
Problem it solves: O(log n) average search/insert/delete with a much simpler implementation than a self-balancing tree, and better suitability for concurrent access patterns.
Why previous structures are insufficient:
- Plain Linked List: O(n) for search β no shortcuts of any kind.
- AVL/Red-Black Tree: O(log n) guaranteed, but rotation logic is genuinely intricate (as seen in Chapter 7 β four distinct cases, careful pointer surgery) and hard to parallelize safely.
- Array/Sorted Array: O(log n) search via binary search, but O(n) insert/delete due to shifting.
Trade-offs:
- You gain O(log n) expected (probabilistic, not strictly guaranteed) performance with dramatically simpler code β no rotations, just randomized level assignment and standard linked-list pointer relinking.
- You lose the guarantee β a Skip Listβs O(log n) is an expected/average bound backed by probability, not an absolute worst-case guarantee like AVLβs. An extremely unlucky sequence of random coin flips (astronomically rare in practice) could, in theory, produce a poorly-structured skip list. You also pay extra memory for the multiple levels of pointers per node.
3. Internal Working
Structure β multiple linked lists stacked, each level a βsparserβ version of the one below:
Level 3: HEAD -------------------------> 50 -----------------------------> NIL
Level 2: HEAD -----------> 20 --------> 50 --------> 70 ------------------> NIL
Level 1: HEAD -----> 10 -> 20 -> 30 --> 50 --> 60 -> 70 --------> 90 ------> NIL
Level 0: HEAD -> 5 -> 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70 -> 80 -> 90 -> NIL
Level 0 is a complete, ordinary sorted linked list containing every element. Each higher level contains a random subset of the level below β in the classic design, each element independently has (typically) a 50% chance of being βpromotedβ to the next level up, which is what produces the expected geometric thinning (level 1 has roughly n/2 elements, level 2 roughly n/4, and so on).
Search for 60, step by step (starting from the top level, moving right as far as possible without overshooting, then dropping down a level):
Level 3: HEAD -> 50 (50 < 60, can go further?) -> NIL is next, would overshoot -> drop to level 2 at node 50
Level 2: at 50 -> 70 (70 > 60, overshoot!) -> drop to level 1, staying at 50
Level 1: at 50 -> 60 (60 == 60, FOUND!)
Only 4 comparisons touched, skipping entirely over 10, 20, 30, 40 β the βexpress laneβ effect in action.
Randomized level assignment on insert: when inserting a new element, flip a (virtual) coin repeatedly β heads, promote to the next level up; tails, stop. This is what gives each level roughly half the elements of the level below, in expectation, without any explicit rebalancing logic.
4. Operations
Search(value):
- Start at the top-left (head of the highest level).
- At each level, move right as long as the next nodeβs value is β€ target and doesnβt overshoot; when moving right would overshoot (or hit the end), drop down one level and repeat.
- Stop when either the value is found, or level 0 is exhausted without a match.
- Expected O(log n).
Insert(value):
- Perform a search, tracking the last node visited at each level (these become the new nodeβs predecessors).
- Randomly determine the new nodeβs height (via repeated coin flips, or equivalently, counting trailing 1-bits of a random number).
- Splice the new node into every level up to its assigned height, using the tracked predecessors from the search.
- Expected O(log n).
Delete(value):
- Perform a search, tracking predecessors at each level (same as insert).
- Unlink the node from every level it appears in.
- Expected O(log n).
Range Query / Traverse:
- Level 0 alone is a complete sorted linked list β traversing it gives sorted output, just like a BSTβs in-order traversal, in O(n).
5. Time & Space Complexity
| Operation | Expected (Average) | Worst Case (extremely unlikely) | Space Complexity |
|---|---|---|---|
| Search | O(log n) | O(n) | O(1) extra |
| Insert | O(log n) | O(n) | O(1) extra per node (proportional to assigned height) |
| Delete | O(log n) | O(n) | O(1) extra |
| Overall storage | β | β | O(n) expected (roughly 2n total pointers across all levels, since each level has about half the elements of the one below) |
Why these hold:
- The expected O(log n) comes directly from the probabilistic level-assignment scheme: with each level expected to contain about half the elements of the level below, the number of levels needed to cover n elements is expected to be O(log n) β mirroring a balanced treeβs height, but achieved through randomness rather than enforced structure.
- The worst case is technically O(n) β if, by sheer bad luck, every coin flip came up βpromoteβ (or every element ended up at level 0 only), the structure could degenerate toward a plain linked list. This is why Skip Lists are described as giving expected / average-case guarantees, not the absolute worst-case guarantees an AVL Tree provides β a distinction worth being precise about in an interview.
- Space is O(n) expected β the geometric thinning (each level roughly halves the element count) means total pointers across all levels sum to roughly 2n, a small constant multiple of a plain linked listβs memory.
6. Advantages
- Expected O(log n) search/insert/delete with dramatically simpler code than a self-balancing tree β no rotation logic, just randomized level assignment and standard linked-list splicing.
- Naturally suited to concurrent/lock-free implementations β a major reason Skip Lists are chosen in some high-performance systems over trees, since balancing rotations are hard to parallelize safely.
- Supports efficient range queries (level 0 is a full sorted linked list).
7. Disadvantages
- No absolute worst-case guarantee β only probabilistic/expected bounds (astronomically unlikely, but theoretically possible, degenerate cases exist).
- Extra memory for multiple levels of pointers per node, though modest in expectation (~2x a plain linked list).
- Randomness makes the structureβs exact shape non-deterministic β harder to reason about or debug precisely compared to a deterministic tree structure.
8. Real-World Applications
- Databases/Storage Engines: Redis uses Skip Lists internally to implement its Sorted Set data type, specifically because of the combination of O(log n) average performance and simplicity/concurrency-friendliness.
- Concurrent Programming: Javaβs
ConcurrentSkipListMapandConcurrentSkipListSetuse Skip Lists specifically because theyβre easier to make thread-safe (via fine-grained or lock-free techniques) than a balanced tree. - LevelDB / RocksDB (key-value storage engines): Use Skip-List-based structures (
MemTable) for the in-memory write buffer, valuing the simplicity and good average-case performance for a component thatβs rebuilt/flushed frequently. - Networking: Some routing/lookup structures favor Skip Lists for their simplicity in probabilistic or approximate contexts.
9. Implementation (C++17)
#include <iostream>
#include <vector>
#include <cstdlib>
#include <memory>
class SkipList {
private:
struct Node {
int value;
std::vector<Node*> forward; // forward[i] = pointer at level i
Node(int val, int level) : value(val), forward(level + 1, nullptr) {}
};
static constexpr int MAX_LEVEL = 16;
static constexpr float PROBABILITY = 0.5f;
Node* head;
int currentLevel;
// Randomly determine a new node's level via repeated "coin flips."
int randomLevel() {
int level = 0;
while (static_cast<float>(rand()) / RAND_MAX < PROBABILITY && level < MAX_LEVEL) {
level++;
}
return level;
}
public:
SkipList() : currentLevel(0) {
head = new Node(-1, MAX_LEVEL); // sentinel head, present at every level
}
~SkipList() {
Node* current = head->forward[0];
while (current) {
Node* next = current->forward[0];
delete current;
current = next;
}
delete head;
}
// Search. Expected O(log n).
bool search(int target) {
Node* current = head;
for (int i = currentLevel; i >= 0; --i) {
while (current->forward[i] && current->forward[i]->value < target) {
current = current->forward[i]; // move right as far as possible at this level
}
// about to overshoot or hit end -> drop down a level
}
current = current->forward[0];
return current != nullptr && current->value == target;
}
// Insert. Expected O(log n).
void insert(int value) {
std::vector<Node*> update(MAX_LEVEL + 1, head); // tracks the predecessor at EACH level
Node* current = head;
for (int i = currentLevel; i >= 0; --i) {
while (current->forward[i] && current->forward[i]->value < value) {
current = current->forward[i];
}
update[i] = current; // remember where we dropped down from, at this level
}
int newLevel = randomLevel();
if (newLevel > currentLevel) {
for (int i = currentLevel + 1; i <= newLevel; ++i) {
update[i] = head; // new top levels' predecessor is simply the head
}
currentLevel = newLevel;
}
Node* newNode = new Node(value, newLevel);
for (int i = 0; i <= newLevel; ++i) {
newNode->forward[i] = update[i]->forward[i]; // splice in at every assigned level
update[i]->forward[i] = newNode;
}
}
// Delete. Expected O(log n).
void remove(int value) {
std::vector<Node*> update(MAX_LEVEL + 1, head);
Node* current = head;
for (int i = currentLevel; i >= 0; --i) {
while (current->forward[i] && current->forward[i]->value < value) {
current = current->forward[i];
}
update[i] = current;
}
current = current->forward[0];
if (!current || current->value != value) return; // not found
for (int i = 0; i <= currentLevel; ++i) {
if (update[i]->forward[i] != current) break; // this level doesn't contain the node
update[i]->forward[i] = current->forward[i]; // unlink at this level
}
delete current;
while (currentLevel > 0 && head->forward[currentLevel] == nullptr) {
currentLevel--; // shrink if the top level(s) became empty
}
}
};
// Example usage
int main() {
SkipList list;
for (int v : {30, 10, 50, 20, 40}) {
list.insert(v);
}
std::cout << "search(40): " << list.search(40) << "\n"; // 1 (true)
std::cout << "search(25): " << list.search(25) << "\n"; // 0 (false)
list.remove(30);
std::cout << "search(30) after remove: " << list.search(30) << "\n"; // 0 (false)
return 0;
}
10. Code Walkthrough
Node::forwardas avector<Node*>: Each node holds one forward pointer per level it participates in β a node assigned level 2 hasforward.size() == 3(levels 0, 1, 2). This variable-length-per-node structure is exactly what makes memory usage proportional to the (randomized) sum of assigned heights, not a fixed multiple per node.randomLevelβs coin-flip loop: Each iteration is like a coin flip withPROBABILITYchance of βpromoteβ β this directly implements the geometric distribution described in section 3, capped atMAX_LEVELto bound worst-case memory in pathological (extremely unlucky) cases.searchβs βmove right, then drop downβ double loop: The outer loop walks levels top-down; the innerwhilegreedily moves right within a level as far as possible without overshooting β this is the literal implementation of the βexpress lane, then drop to localβ analogy from section 1.insertβsupdate[]array: Tracks, for every level, the last node visited before dropping down β these become the new nodeβs predecessors at each level once its random height is determined. This is conceptually identical to how youβd track βthe node just before the insertion pointβ in a plain linked list insert, just replicated across multiple levels.insertβs level-growth handling (if (newLevel > currentLevel)): If the new nodeβs randomly assigned height exceeds every existing nodeβs height, the listβscurrentLevelitself grows, and the new top levelsβ only βpredecessorβ is trivially the head (since nothing else exists at that height yet).removeβsif (update[i]->forward[i] != current) break;: This check handles the fact that a node being deleted might not appear at every level up tocurrentLevelβ once we reach a level where the node under deletion isnβt the very next node, we know it doesnβt participate in that level (or above), so we stop unlinking.
Common mistakes to watch for here:
- Forgetting to track predecessors at every level during insert/delete, not just the level(s) the target node ultimately occupies.
- Not shrinking
currentLevelafter deletions empty out the top level(s), leaving wasted iteration in future searches. - Using a fixed (non-random) promotion pattern, defeating the entire probabilistic balance guarantee.
11. Dry Run
Insert 30, 10, 50, 20, 40 (assume, for a clean illustrative dry run, that random level assignment gives: 30βlevel1, 10βlevel0, 50βlevel2, 20βlevel0, 40βlevel1):
| After inserting | Level 2 | Level 1 | Level 0 (full sorted list) |
|---|---|---|---|
| 30 (level 1) | β | 30 | 30 |
| 10 (level 0) | β | 30 | 10, 30 |
| 50 (level 2) | 50 | 30, 50 | 10, 30, 50 |
| 20 (level 0) | 50 | 30, 50 | 10, 20, 30, 50 |
| 40 (level 1) | 50 | 30, 40, 50 | 10, 20, 30, 40, 50 |
Search(40):
Level 2 (currentLevel=2): head -> 50. 50 > 40, don't move. Drop to level 1.
Level 1: head -> 30 (30<40, move) -> 40 (40==40 stop moving, but check next)...
at 30, forward[1]=40, 40 < 40? No (equal, not strictly less) -> stop moving right, drop to level 0.
Level 0: at 30 -> 40. current->forward[0]=40, value 40, match!
Final check: current = current->forward[0] = node(40). value==target -> TRUE.
Only touched nodes 50 (level 2), 30 and 40 (level 1), 40 (level 0) β 3-4 comparisons versus 5 for a full linear scan; the advantage compounds dramatically for larger n.
12. Interview Questions
Conceptual:
- Why is a Skip Listβs O(log n) bound βexpected,β not guaranteed, unlike an AVL Tree?
- Explain how randomized level assignment substitutes for explicit tree rotations.
- Why are Skip Lists considered easier to make thread-safe/concurrent than balanced trees?
- Whatβs the expected total memory overhead of a Skip List compared to a plain linked list?
- Compare Skip List vs. AVL Tree vs. Hash Table for a sorted-set use case β trade-offs of each.
Coding:
- Implement a Skip Listβs search, insert, and delete (LeetCode 1206 β Design Skip List).
- Implement a sorted set backed by a Skip List supporting rank queries (whatβs the Kth smallest element?).
- Design a Redis-style sorted set (Skip List + Hash Map combo, mirroring Redisβs actual implementation).
Follow-ups / interviewer traps:
- βWhat happens in the theoretical worst case where every coin flip favors maximum promotion?β (tests honest acknowledgment of the O(n) worst case, and why itβs astronomically unlikely rather than impossible)
- βHow would you make Insert/Delete safe for concurrent access?β (tests awareness that per-level fine-grained locking, or lock-free CAS-based techniques, are much more tractable here than for a rotating tree)
13. Practice Problems
Medium/Hard
- Design Skip List (LeetCode 1206)
- Design a sorted data structure supporting rank/order-statistics queries (extension exercise)
Skip Lists are less common as standalone LeetCode problems (more of a βexplain and implement from scratchβ systems/interview topic) β the highest-value practice is implementing one fully from scratch and stress-testing it against a plain sorted array or std::set for correctness, plus reading Redisβs actual sorted-set source for a real production example.
Also recommended: GeeksforGeeks βSkip Listβ practice/theory set; William Pughβs original 1990 paper (βSkip Lists: A Probabilistic Alternative to Balanced Treesβ) is short, readable, and a genuinely worthwhile primary source.
14. Common Mistakes
- Confusing βexpected O(log n)β with a hard guarantee β a Skip Listβs worst case is technically O(n), just vanishingly unlikely with proper randomization.
- Forgetting to track predecessors at every level during insert/delete, corrupting the structure at levels above the immediately obvious one.
- Using a bad or predictable random number source, undermining the probabilistic balance the entire structure depends on.
- Not capping
MAX_LEVEL, risking pathological memory usage in rare unlucky cases (or capping it too low for the expected dataset size, which increases the constant factor in practice). - Forgetting to shrink
currentLevelafter deletions, leaving dead levels that add small but unnecessary overhead to every subsequent search.
15. Summary
Key takeaways:
- A Skip List achieves expected O(log n) search/insert/delete using randomized βexpress laneβ levels layered over a base sorted linked list β no rotations required.
- The trade-off versus AVL/Red-Black Trees is guaranteed-worst-case (trees) vs. simpler-code-and-concurrency-friendliness (skip lists) β both achieve the same expected asymptotic performance.
- Redisβs Sorted Set and Javaβs
ConcurrentSkipListMapare the most prominent real-world validations of this design.
Complexity recap:
| Operation | Expected Time | Worst Case | Space |
|---|---|---|---|
| Search / Insert / Delete | O(log n) | O(n) (astronomically unlikely) | O(n) expected |
Decision guideline: Choose a Skip List when you want BST-like average performance with much simpler implementation than a self-balancing tree, especially in concurrent/multi-threaded contexts. Choose an AVL/Red-Black Tree instead when you need an absolute worst-case guarantee, not just a probabilistic one (e.g., real-time systems with hard latency bounds).
Next chapter: 18_bloom_filter.md, followed by the capstone 19_lru_cache.md.
Chapter 18: Bloom Filter (Overview)
Study time: ~4-5 hours | Prerequisite: Hash Tables, basic probability | Difficulty: Intermediate-Advanced
1. Introduction
Definition: A Bloom Filter is a space-efficient probabilistic data structure that answers βhave I possibly seen this element before?β It can have false positives (saying βmaybe presentβ when the element was never actually added) but never false negatives (if it says βdefinitely not present,β thatβs always correct).
Purpose: To test set membership using dramatically less memory than a Hash Set, at the cost of occasional false positives β ideal when you need a fast, cheap βprobably not thereβ filter before doing a more expensive definitive check.
Real-world analogy: A bouncer with a rough mental list of βtroublemakersβ who only remembers a blurry impression of faces, not exact identities. If the impression doesnβt match anyone on the list, the person is definitely let in β no possible mistake there. But if the blurry impression does seem to match, the bouncer might occasionally flag an innocent person by mistake (a false positive) β theyβd need a proper ID check (a slower, definitive lookup) to be sure. What a Bloom Filter guarantees is that it will never mistakenly wave through an actual troublemaker.
Motivation: Storing millions or billions of items in a Hash Set to check membership can require enormous memory. Many applications only need a fast first-pass filter β βis it worth doing the expensive check at all?β β where occasionally checking a few extra non-members is an acceptable cost, but ever missing an actual member would be unacceptable.
History: Invented by Burton Howard Bloom in 1970, originally to reduce the disk-access cost of hyphenation dictionaries; now foundational to databases, networking, and distributed systems.
2. Why Do We Need It?
Problem it solves: Space-efficient approximate set-membership testing, when you can tolerate rare false positives but require zero false negatives.
Why previous structures are insufficient:
- Hash Set: Exact, no false positives/negatives β but stores every element (or at least its hash) explicitly, costing memory proportional to the number of elements, often dozens of bytes per entry.
- Sorted Array / BST: Also exact, but similarly memory-proportional to element count, and slower (O(log n)) besides.
A Bloom Filter breaks the βmemory proportional to elements storedβ constraint entirely β its size is fixed upfront based on expected element count and desired false-positive rate, and stays constant regardless of how βlargeβ the actual elements are (a Bloom Filter storing membership for million-character strings uses exactly the same memory as one storing single characters).
Trade-offs:
- You gain massive memory savings β often 10x or more smaller than an equivalent Hash Set β and O(1) (technically O(k), a small constant) insert/query time.
- You pay for it with an irreversible trade: false positives are possible (and their rate is tunable but never zero for a fixed-size filter), and you cannot remove elements from a standard Bloom Filter (a variant, the Counting Bloom Filter, adds limited deletion support at extra memory cost).
3. Internal Working
Structure: A bit array of size m (all bits initially 0), plus k independent hash functions.
Insert(x): compute k hash values of x, each mapped to an index in [0, m), and set all k of those bit positions to 1.
Bit array (m=10), k=3 hash functions. Insert "cat":
hash1("cat") % 10 = 1
hash2("cat") % 10 = 4
hash3("cat") % 10 = 7
Before: [0,0,0,0,0,0,0,0,0,0]
After: [0,1,0,0,1,0,0,1,0,0] β bits 1, 4, 7 set to 1
Insert βdogβ (different hash values, some may overlap with existing 1-bits):
hash1("dog") % 10 = 2
hash2("dog") % 10 = 4 β COLLIDES with "cat"'s bit 4, already 1
hash3("dog") % 10 = 8
Before: [0,1,0,0,1,0,0,1,0,0]
After: [0,1,1,0,1,0,0,1,1,0] β bits 2 and 8 newly set; bit 4 was already 1
Query(βcatβ): compute the same 3 hash positions (1, 4, 7) β check if all are 1. Yes β βpossibly presentβ (correctly, since we did insert it).
Query(βbirdβ) (never inserted): compute its 3 hash positions, say (2, 4, 9). Check: bit 2 = 1 β, bit 4 = 1 β, bit 9 = 0 β β at least one bit is 0 β βdefinitely NOT present.β Correct β βbirdβ was never added.
Query(βfoxβ) (never inserted, but a false positive scenario): suppose its 3 hash positions happen to be (1, 2, 8) β purely by coincidence of hashing, all three already happen to be 1 (from βcatβ and βdogββs combined insertions) β the filter reports βpossibly presentβ even though βfoxβ was never actually added. This is the false positive β an unavoidable consequence of multiple elementsβ hash bits overlapping in a finite bit array.
Why no false negatives are possible: every bit that was ever set to 1 by an actual insertion stays 1 forever (thereβs no way to βunsetβ a bit safely, since other elements might share it) β so if an element was truly inserted, all its k bits are guaranteed to still be 1 when queried later. A βdefinitely not presentβ answer can only occur when at least one bit is still 0, which can only be true if that exact combination of bits was never set β meaning the element (or an unlucky collision) genuinely was never inserted.
4. Operations
Insert(x):
- Compute
khash values ofx, each reduced modmto a bit-array index. - Set all
kcorresponding bits to 1 (if already 1, no change β idempotent). - O(k), effectively O(1) for fixed k.
Query(x) β βMightContainβ:
- Compute the same
khash values/indices. - If any of the k bits is 0 β return definitely not present.
- If all k bits are 1 β return possibly present (could be a true positive or a false positive).
- O(k), effectively O(1).
Delete: Not supported in a standard Bloom Filter β unsetting a bit could incorrectly cause a false negative for some other element that happens to share that bit. (The Counting Bloom Filter variant replaces each bit with a small counter, allowing safe decrement-based deletion, at proportionally more memory.)
Tuning m and k: Given an expected number of elements n and a desired false-positive rate p, standard formulas give the optimal bit-array size m β -(nΒ·ln p)/(ln 2)Β² and optimal hash count k β (m/n)Β·ln 2. Choosing these well is essential β too few bits or too few/many hash functions all degrade the false-positive rate.
5. Time & Space Complexity
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Insert | O(k) β O(1) | β |
| Query | O(k) β O(1) | β |
| Overall storage | β | O(m) bits, independent of element size, and roughly O(n) bits total for a tuned filter (a small constant number of bits per expected element, NOT per byte of the elementβs actual data) |
Why these hold:
- Both operations only ever touch exactly
kbit positions β a small, fixed constant chosen at design time β regardless of how many elements are already in the filter or how large the target dataset is. This is the fundamental reason Bloom Filters scale so well: cost per operation never grows withn. - The bit arrayβs size
mis chosen upfront based on expected capacity and tolerable false-positive rate β critically, independent of the size of the elements themselves. A Bloom Filter of URLs (each potentially very long strings) uses exactly the same memory as one of single integers, since only a fixed-size hash (not the original element) ever gets stored. - The false-positive rate rises predictably as more elements are inserted beyond the filterβs tuned capacity (more bits get set to 1, increasing accidental all-1 collisions) β this is a graceful, well-understood degradation, not a sudden failure.
6. Advantages
- Extremely space-efficient β often an order of magnitude (or more) smaller than a Hash Set for the same membership-testing task.
- O(1) (technically O(k)) insert and query β among the fastest possible operations.
- Memory usage is independent of element size β testing membership of huge strings/objects costs the same as testing small ones.
- Tunable false-positive rate β you can trade memory for accuracy along a well-understood mathematical curve.
7. Disadvantages
- False positives are possible and unavoidable for a fixed-size filter (though the rate is tunable and can be made arbitrarily small at the cost of more memory).
- No deletion support in the standard version (Counting Bloom Filter needed for that, at extra memory cost).
- Cannot enumerate the actual elements stored β it only answers membership queries, nothing else (no traversal, no βgive me all elementsβ).
- Choosing
mandkwell requires knowing (or estimating) the expected number of elements in advance; a badly undersized filter degrades toward βeverything looks present.β
8. Real-World Applications
- Databases: Many databases (Cassandra, HBase, Bigtable-style systems) use Bloom Filters to quickly check βmight this key exist in this data file?β before doing an expensive disk read β avoiding wasted I/O for keys that definitely arenβt present.
- Networking: Detecting duplicate packets, or checking membership in large blocklists/allowlists without storing every entry explicitly.
- Web Browsers: Google Chrome historically used a Bloom Filter to check URLs against a local list of known-malicious sites before making a slower, more thorough server-side check (avoiding a network round-trip for the vast majority of definitely-safe URLs).
- Distributed Systems / Caching: Quickly checking βis this cache key definitely absent?β before querying a slower backing store β a very common cache-miss optimization pattern.
- Spell Checkers: An early, memory-efficient way to check βis this word definitely not in the dictionary?β before a more expensive lookup.
- Bioinformatics: Efficiently checking membership of massive DNA/genome sequence sets, where memory constraints are severe.
- Blockchain/Cryptocurrency: Some lightweight clients use Bloom Filters to privately request βtransactions that might be relevant to meβ without revealing exactly which addresses theyβre tracking.
9. Implementation (C++17)
#include <iostream>
#include <vector>
#include <string>
#include <functional>
#include <cmath>
class BloomFilter {
private:
std::vector<bool> bits;
size_t m; // bit array size
size_t k; // number of hash functions
// Generate the i-th hash value by combining a base hash with a salt (double hashing technique) β
// a standard trick to simulate k independent hash functions from just two real ones.
size_t hashI(const std::string& item, size_t i) const {
std::hash<std::string> hasher;
size_t h1 = hasher(item);
size_t h2 = std::hash<std::string>{}(item + "_salt"); // a second, differently-seeded hash
return (h1 + i * h2) % m;
}
public:
// n = expected number of elements, p = desired false-positive rate (e.g., 0.01 for 1%)
BloomFilter(size_t n, double p) {
m = static_cast<size_t>(std::ceil(-(static_cast<double>(n) * std::log(p)) / (std::log(2) * std::log(2))));
k = static_cast<size_t>(std::round((static_cast<double>(m) / n) * std::log(2)));
if (k < 1) k = 1;
bits.assign(m, false);
}
// Insert an element. O(k).
void insert(const std::string& item) {
for (size_t i = 0; i < k; ++i) {
bits[hashI(item, i)] = true;
}
}
// Query membership. O(k). Returns false ONLY if definitely absent; true means "possibly present."
bool mightContain(const std::string& item) const {
for (size_t i = 0; i < k; ++i) {
if (!bits[hashI(item, i)]) {
return false; // any 0 bit proves definite absence
}
}
return true; // all k bits were 1 β possibly present (or a false positive)
}
size_t bitArraySize() const { return m; }
size_t numHashFunctions() const { return k; }
};
// Example usage
int main() {
// Tuned for ~1000 expected elements, 1% false-positive rate.
BloomFilter filter(1000, 0.01);
std::cout << "Bit array size: " << filter.bitArraySize()
<< ", hash functions: " << filter.numHashFunctions() << "\n";
filter.insert("cat");
filter.insert("dog");
filter.insert("elephant");
std::cout << "Might contain 'cat'? " << filter.mightContain("cat") << "\n"; // 1 (true)
std::cout << "Might contain 'dog'? " << filter.mightContain("dog") << "\n"; // 1 (true)
std::cout << "Might contain 'giraffe'? " << filter.mightContain("giraffe") << "\n"; // 0 (false) β almost certainly correct
std::cout << "Might contain 'zebra'? " << filter.mightContain("zebra") << "\n"; // 0 (false), OR occasionally 1 (a false positive)
return 0;
}
10. Code Walkthrough
hashIvia double hashing: Rather than writingkgenuinely independent hash functions from scratch, the standard practical trick combines just two base hashes (h1,h2) ash1 + i*h2fori = 0..k-1β this is provably βgood enoughβ to simulate k independent hash functions for Bloom Filter purposes, and is far simpler than maintaining k separate hash implementations.- Constructorβs
mandkformulas: These directly implement the standard tuning formulas from section 4 β given the expected element countnand desired false-positive ratep, they compute the bit-array size and hash-function count that minimize memory while hitting the target false-positive rate. Getting this tuning right upfront is the single most important design decision when using a Bloom Filter. insert: Simply sets allkcomputed bit positions totrueβ note thereβs no βcheck if already setβ logic needed, since setting an already-1 bit to 1 again is a harmless no-op (this idempotency is part of why insert is safe to call redundantly).mightContain: The short-circuitreturn falsethe moment any bit is found to be 0 is the crux of the whole βno false negativesβ guarantee β a single 0 bit is airtight proof of absence, so thereβs no need to check the remaining bits once one is found unset.
Common mistakes to watch for here:
- Using genuinely correlated (non-independent-enough) hash functions, which inflates the real-world false-positive rate above the theoretical tuned value.
- Under-provisioning
mfor the actual number of elements inserted (inserting far more than thenused to tune the filter) β this silently degrades the false-positive rate well beyond what was intended. - Attempting to delete an element by unsetting its bits directly β this can introduce false negatives for any other element sharing those bits, breaking the structureβs core guarantee.
11. Dry Run
Setup: m=10 bits, k=3 hash functions (matching section 3βs example). Insert βcatβ (bits 1,4,7), insert βdogβ (bits 2,4,8).
| Step | Bit array (index 0-9) |
|---|---|
| init | 0000000000 |
| insert βcatβ (bits 1,4,7) | 0100100100 |
| insert βdogβ (bits 2,4,8) | 0110100110 |
Query βcatβ (bits 1,4,7): check bit1=1 β, bit4=1 β, bit7=1 β β all set β βpossibly presentβ (correct β a true positive, since βcatβ really was inserted).
Query βbirdβ (suppose its bits are 3,5,9): check bit3=0 β immediately return βdefinitely NOT presentβ (correct β βbirdβ was never inserted; the very first 0 bit found is proof enough, no need to check bits 5 and 9 at all).
Query βfoxβ (suppose, by unlucky coincidence, its bits are exactly 1,2,8): check bit1=1 β, bit2=1 β, bit8=1 β β all set β βpossibly presentβ β but βfoxβ was never actually inserted! This is a false positive, arising purely because βfoxββs three hash positions happened to exactly match a combination of bits already set by βcatβ and βdogββs separate insertions.
12. Interview Questions
Conceptual:
- Why can a Bloom Filter never produce a false negative, but can produce false positives?
- Walk through the formulas for choosing
m(bit array size) andk(number of hash functions) given expected element count and desired false-positive rate. - Why canβt you delete an element from a standard Bloom Filter? How does a Counting Bloom Filter solve this?
- Compare a Bloom Filter to a Hash Set for membership testing β whatβs the fundamental trade-off?
- What happens to the false-positive rate as you insert more elements than the filter was tuned for?
Coding:
- Implement a Bloom Filter with configurable size and hash count.
- Design a Counting Bloom Filter supporting deletion.
- Design a system to check if a URL is potentially malicious using a Bloom Filter as a first-pass filter (system-design style question).
- Given a stream of items, estimate how many distinct items have been seen using a Bloom-Filter-adjacent technique (related to but distinct from a plain Bloom Filter β tests awareness of the broader βprobabilistic data structuresβ family, e.g., HyperLogLog).
Follow-ups / interviewer traps:
- βYour Bloom Filterβs false-positive rate is too high in production β what are your options?β (expects: increase
m, retunek, or create a fresh larger filter and migrate β cannot simply βfixβ an existing undersized filter in place) - βCan two Bloom Filters be merged (e.g., for a distributed system)?β (yes, if theyβre the same size
mand use the same hash functions β a bitwise OR of the two bit arrays correctly represents the union of both sets, with a combined false-positive rate) - βWhy not just use a smaller Hash Set instead?β (tests understanding that a Hash Setβs minimum memory is bounded by needing to store enough information to be exact β a Bloom Filter deliberately discounts a small amount of exactness for a much better memory ratio)
13. Practice Problems
Bloom Filters are primarily a systems-design/probabilistic-data-structures topic rather than a classic LeetCode-style coding target, but related practice includes:
- Implement a Bloom Filter from scratch with tunable parameters (the exercise in section 9).
- Design a URL shortener / web crawler deduplication system using a Bloom Filter as a first-pass check (system design).
- GeeksforGeeks βBloom Filtersβ practice/theory set.
- Explore related probabilistic structures for contrast: HyperLogLog (cardinality estimation), Count-Min Sketch (frequency estimation) β same underlying philosophy of trading a small, tunable amount of accuracy for large memory savings.
14. Common Mistakes
- Assuming zero false positives are possible β they are an inherent, unavoidable property of any fixed-size Bloom Filter; only the rate is tunable, never eliminated entirely (barring an infinitely large filter).
- Attempting in-place deletion by unsetting bits β breaks the no-false-negative guarantee for other elements sharing those bits.
- Under-provisioning capacity β inserting far more elements than the filter was tuned for silently and severely degrades accuracy.
- Using poorly-distributed or correlated hash functions β undermines the mathematical guarantees the tuning formulas rely on.
- Treating a Bloom Filter as a complete replacement for exact storage β it should typically be paired with a slower, authoritative store for confirming actual positives, not used as the sole source of truth.
15. Summary
Key takeaways:
- A Bloom Filter trades a small, tunable false-positive rate for massive memory savings over an exact Hash Set β and crucially, it never produces false negatives.
- Insert and query are both O(k), a small fixed constant, regardless of dataset size or element size.
- No deletion support in the standard version; no ability to enumerate stored elements β it answers exactly one question (βmight this be present?β) extremely efficiently, and nothing else.
- Widely used as a fast βis it even worth checking further?β pre-filter in databases, networking, and browsers.
Complexity recap:
| Operation | Time | Space |
|---|---|---|
| Insert | O(k) | β |
| Query | O(k) | O(m) bits total, tuned via n and desired false-positive rate p |
Decision guideline: Reach for a Bloom Filter when you need extremely memory-efficient approximate membership testing, can tolerate a small, tunable false-positive rate, and never need exact answers or deletion. Pair it with a slower, authoritative structure to resolve βpossibly presentβ results definitively when needed. If you need exact answers or deletion support, use a Hash Set instead.
Next chapter: 19_lru_cache.md β the capstone project, combining Hash Map + Doubly Linked List.
Chapter 19: LRU Cache (Capstone)
Study time: ~5-6 hours | Prerequisite: Hash Table (Ch. 5), Doubly Linked List (Ch. 2) | Difficulty: Advanced This is the capstone project for the entire guide β it combines two data structures from opposite ends of the roadmap into one elegant, O(1)-everything design.
1. Introduction
Definition: An LRU (Least Recently Used) Cache is a fixed-capacity key-value store that, when full, evicts the item that hasnβt been accessed for the longest time to make room for a new one β both get and put must run in O(1).
Purpose: To keep a bounded amount of βhotβ (frequently/recently used) data readily available, automatically discarding the βcoldestβ (least recently touched) data when space runs out β without ever scanning the whole cache to decide what to evict.
Real-world analogy: Your work desk has limited space. You keep the documents youβre actively using right in front of you; when a new document arrives and your desk is full, you file away whichever document you havenβt touched in the longest time β not necessarily the oldest one you ever put there, but the one thatβs gone the longest without being looked at again.
Motivation: Caches speed up systems by keeping frequently-accessed data close at hand (in fast memory) instead of re-fetching it from a slow source (disk, network, database) every time. But memory is finite β you need an eviction policy for when the cache is full, and LRU is the most widely used policy because βrecently usedβ is usually a strong predictor of βwill be used again soonβ (this assumption is called temporal locality, and it holds remarkably well for most real workloads).
History: LRU caching is a foundational concept in operating systems (virtual memory page replacement) dating to the 1960s, and remains the default or near-default cache eviction policy across nearly every layer of modern computing.
2. Why Do We Need It?
Problem it solves: Bounded-memory caching with an eviction policy that requires no scanning to decide what to remove β both lookup and the recency-tracking update must be O(1), or the cache itself becomes the bottleneck it was meant to eliminate.
Why previous structures are insufficient on their own:
- Hash Map alone: O(1) lookup, but has no concept of βaccess orderβ β youβd need O(n) to scan for the least-recently-used item when eviction is needed.
- Doubly Linked List alone (ordered by recency): O(1) to move an item to the βmost recentβ end, but O(n) to find that item in the first place (no fast lookup by key).
- Array (ordered by recency): same fundamental issue β moving an item to the front/back requires knowing its position, and finding that position is O(n).
The key insight β and the entire point of this capstone chapter: neither structure alone can give you O(1) for both βfind by keyβ and βtrack/update recency order.β Combining them β a Hash Map for O(1) lookup, pointing directly at nodes in a Doubly Linked List for O(1) recency reordering β gives you both simultaneously. This is precisely why the guide placed Hash Tables (Chapter 5) and Doubly Linked Lists (Chapter 2) where it did: this capstone is their natural convergence point.
Trade-offs:
- You gain O(1)
getandput, including eviction β genuinely as fast as a cache can be. - You pay for it with the combined memory overhead of both structures (hash map entries and linked list node pointers) and meaningfully more implementation care than either structure alone (keeping both structures perfectly in sync on every operation is the whole challenge).
3. Internal Working
The combined structure:
HashMap<Key, Node*> ββpoints directly intoβββΆ Doubly Linked List (ordered by recency)
MOST RECENT LEAST RECENT
head (dummy) β· [key3:val] β· [key1:val] β· [key2:val] β· tail (dummy)
The list is kept ordered by recency at all times: the head side holds the most-recently-used item; the tail side holds the least-recently-used item β the one that gets evicted first when the cache is full. Using dummy head/tail sentinel nodes (holding no real data) simplifies the pointer logic, since every real node then always has a genuine non-null neighbor on both sides, eliminating special-case checks for βis this the very first/last real node?β
get(key) β walkthrough:
get("key1"):
1. HashMap lookup: "key1" β pointer to its node in the linked list. O(1).
2. Found! This access makes "key1" the MOST recently used β move its node
to right after head (the "most recent" position). O(1), pure pointer surgery,
no searching required since we already have a direct pointer to the node.
3. Return the value.
Before: head β· [key3] β· [key1] β· [key2] β· tail
After: head β· [key1] β· [key3] β· [key2] β· tail
β² moved to front
put(key, value) when the cache is FULL β walkthrough:
Cache capacity 3, currently: head β· [key1] β· [key3] β· [key2] β· tail (key2 is least recent)
put("key4", val4):
1. Cache is full (size == capacity) β must evict.
2. The LEAST recently used item is always right before tail β that's key2. Remove it:
both from the linked list (O(1), direct pointer) AND from the hash map (O(1) key-based delete).
3. Insert the new node for key4 right after head (it's now the most recent).
4. Add "key4" -> node pointer into the hash map.
After: head β· [key4] β· [key1] β· [key3] β· tail (key2 evicted)
4. Operations
get(key):
- Hash map lookup for the node. O(1).
- If not found, return βnot presentβ (a cache miss).
- If found: unlink the node from its current position and relink it right after
head(marking it most-recently-used), then return its value. Both steps are O(1) because the hash map gave us a direct pointer β no traversal needed.
put(key, value):
- If the key already exists: update its value, and move its node to right after
head(same βmark as most recentβ logic asget). - If the key is new and the cache has room: create a new node, insert it right after
head, and add the keyβnode mapping to the hash map. - If the key is new and the cache is full: remove the node right before
tail(the least-recently-used item) from both the linked list and the hash map, then insert the new node as above. - All cases: O(1).
Delete/Evict (internal, triggered by put when full):
- Always targets the node adjacent to
tailβ this is guaranteed to be the least-recently-used item, precisely because the list is kept ordered by recency at every step, never needing a scan to find it.
5. Time & Space Complexity
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| get | O(1) | O(1) |
| put (update existing) | O(1) | O(1) |
| put (insert, room available) | O(1) | O(1) |
| put (insert, triggers eviction) | O(1) | O(1) |
| Overall storage | β | O(capacity) β bounded, this is the entire point of a βcacheβ |
Why these hold: Every single operation is O(1) because the hash map eliminates the need to search for a node (direct pointer lookup), and the doubly linked listβs prev/next pointers eliminate the need to shift anything when moving a node to the front or removing one from the back (unlike an array, where βmove to frontβ would mean shifting everything else). This is the exact payoff promised in section 2 β combining the two structuresβ individual O(1) strengths (hash mapβs O(1) lookup, doubly linked listβs O(1) insert/delete-given-a-node) into one design that has no O(n) step anywhere.
6. Advantages
- Every operation β including eviction β is O(1), making it suitable for extremely high-throughput caching layers.
- Conceptually clean once understood: βhash map for lookup, linked list for recency order, keep them in sync.β
- LRU is a well-understood, broadly effective eviction policy that performs well across a very wide range of real-world access patterns (temporal locality is a near-universal property of real workloads).
7. Disadvantages
- More implementation complexity than either structure alone β every operation must correctly update both structures in lockstep; a bug that updates one but not the other silently corrupts the cache.
- LRU can perform poorly for certain access patterns (e.g., a large one-time sequential scan can evict genuinely βhotβ frequently-used items, since βmost recentβ and βmost frequentβ arenβt always the same thing β this is why variants like LFU (Least Frequently Used) or hybrid policies like LRU-K exist for specific workloads).
- Fixed capacity must be chosen upfront (or the underlying structures resized), and choosing it well requires understanding the actual workloadβs working-set size.
8. Real-World Applications
- Operating Systems: Virtual memory page replacement β deciding which memory pages to swap out to disk when RAM is full is a classic LRU (or LRU-approximation) problem.
- Databases: Buffer pool management (e.g., MySQL InnoDBβs buffer pool uses an LRU-based eviction strategy for cached disk pages).
- CDNs / Web Caching: Deciding which cached web assets to evict when cache storage is full.
- Browsers: Caching recently visited pages/resources, evicting the least recently used when storage limits are hit.
- CPU Caches: Hardware cache replacement policies are conceptually LRU-inspired (though real hardware often uses cheaper LRU-approximations due to strict speed/area constraints).
- API/Application-Level Caching: In-memory caching layers (like a local cache in front of Redis or a database) very commonly default to LRU eviction.
- Content Recommendation/Session Management: Keeping a bounded βrecently viewed itemsβ list per user is directly an LRU-style structure.
9. Implementation (C++17)
#include <iostream>
#include <unordered_map>
class LRUCache {
private:
struct Node {
int key, value;
Node* prev;
Node* next;
Node(int k, int v) : key(k), value(v), prev(nullptr), next(nullptr) {}
};
int capacity;
std::unordered_map<int, Node*> cache; // key -> direct pointer to its list node
Node* head; // dummy sentinel: head->next is always the MOST recently used real node
Node* tail; // dummy sentinel: tail->prev is always the LEAST recently used real node
// Detach a node from its current position in the list. O(1) β pure pointer relinking.
void removeNode(Node* node) {
node->prev->next = node->next;
node->next->prev = node->prev;
}
// Insert a node right after head (marking it most-recently-used). O(1).
void insertAtFront(Node* node) {
node->next = head->next;
node->prev = head;
head->next->prev = node;
head->next = node;
}
public:
LRUCache(int cap) : capacity(cap) {
head = new Node(-1, -1); // dummy sentinels hold no real data
tail = new Node(-1, -1);
head->next = tail;
tail->prev = head;
}
~LRUCache() {
Node* current = head;
while (current != nullptr) {
Node* toDelete = current;
current = current->next;
delete toDelete;
}
}
// O(1): hash map lookup + O(1) reposition to front.
int get(int key) {
auto it = cache.find(key);
if (it == cache.end()) return -1; // cache miss
Node* node = it->second;
removeNode(node); // detach from current position
insertAtFront(node); // re-insert as most-recently-used
return node->value;
}
// O(1): update-in-place, or insert-with-possible-eviction.
void put(int key, int value) {
auto it = cache.find(key);
if (it != cache.end()) {
// Key already exists: update value, mark as most recently used.
Node* node = it->second;
node->value = value;
removeNode(node);
insertAtFront(node);
return;
}
if (static_cast<int>(cache.size()) == capacity) {
// Cache full: evict the least-recently-used node (always right before tail).
Node* lru = tail->prev;
removeNode(lru);
cache.erase(lru->key);
delete lru;
}
// Insert the new key as most-recently-used.
Node* newNode = new Node(key, value);
insertAtFront(newNode);
cache[key] = newNode;
}
};
// Example usage
int main() {
LRUCache lru(2); // capacity 2
lru.put(1, 100);
lru.put(2, 200);
std::cout << "get(1): " << lru.get(1) << "\n"; // 100 β also marks key 1 as most recent
lru.put(3, 300); // cache full (1,2) β evicts key 2 (least recently used, since 1 was just accessed)
std::cout << "get(2): " << lru.get(2) << "\n"; // -1 β evicted, cache miss
lru.put(4, 400); // cache full (1,3) β evicts key 1 (least recently used now)
std::cout << "get(1): " << lru.get(1) << "\n"; // -1 β evicted
std::cout << "get(3): " << lru.get(3) << "\n"; // 300 β still present
std::cout << "get(4): " << lru.get(4) << "\n"; // 400 β still present
return 0;
}
10. Code Walkthrough
- Dummy
head/tailsentinels: Neither holds real data β their entire purpose is to eliminate special-case logic. Without them, inserting into an empty list or removing the only remaining node would need extraifbranches to handle βthere is no next/prev node yet.β With sentinels,head->nextandtail->prevare always valid pointers to real nodes (or to each other, if the cache is empty) β this single design choice is what keepsremoveNodeandinsertAtFrontcompletely branch-free. cachemapping key directly to aNode*: This is the crucial link between the two structures β the hash map doesnβt store the value itself, it stores a pointer directly into the linked list, so once we find a key, moving/updating its node is pure O(1) pointer surgery, with zero additional searching.removeNode+insertAtFrontas the two universal building blocks: Notice that bothget(on a hit) andput(on an update, or a fresh insert) ultimately reduce to some combination of these same two operations β βdetach a nodeβ and βplace a node as most-recent.β This is why the whole class stays so short despite handling several distinct scenarios.- Eviction logic (
tail->prev): Because the list is always kept in recency order by every singleget/putoperation, the least-recently-used node is guaranteed to be sitting right beforetailat the exact moment we need to evict β no scan, no search, just a direct pointer dereference. - Order of operations in
putβs eviction branch: NoteremoveNode(lru)andcache.erase(lru->key)happen beforedelete lruβ deleting the node first would leave a dangling pointer in the hash map and cause undefined behavior when later code tries to readlru->key.
Common mistakes to watch for here:
- Forgetting to update the hash map when evicting a node from the linked list (or vice versa) β this desynchronizes the two structures, the single most common LRU Cache bug.
- Not moving a node to the front on a
gethit β this is easy to forget, but itβs essential: agetis itself a βuseβ of that key, and must count toward recency exactly like aputdoes. - Checking capacity after inserting the new node instead of before evicting β can transiently let the cache exceed capacity, or evict the just-inserted node by mistake.
- Deleting a node before removing its entry from the hash map, leaving a dangling pointer.
11. Dry Run
Capacity 2. Operations: put(1,100), put(2,200), get(1), put(3,300), get(2)
| Step | Action | List (most-recent β least-recent) | HashMap keys | Notes |
|---|---|---|---|---|
| 1 | put(1,100) | [1] | {1} | inserted, room available |
| 2 | put(2,200) | [2,1] | {1,2} | inserted at front |
| 3 | get(1) β 100 | [1,2] | {1,2} | key 1 accessed β moved to front |
| 4 | put(3,300) | cache full (size==2) β evict least-recent = 2 (at tail->prev) β then insert 3 β [3,1] | {1,3} | key 2 evicted |
| 5 | get(2) β -1 | [3,1] (unchanged, miss doesnβt reorder) | {1,3} | key 2 no longer present β cache miss |
Final state: keys {1, 3} remain, key 2 was correctly evicted as the least-recently-used item at the moment put(3,300) needed room. β
12. Interview Questions
Conceptual:
- Why does an LRU Cache need both a hash map and a doubly linked list β why canβt either alone achieve O(1) for everything?
- Why specifically a doubly linked list, not a singly linked list?
- Why do dummy head/tail sentinel nodes simplify the implementation?
- What real-world access pattern could make LRU perform worse than a simpler policy (e.g., FIFO)? (Sequential one-time scans that donβt repeat.)
- How would you extend this design to an LFU (Least Frequently Used) Cache instead β what would need to change?
Coding:
- Implement LRU Cache from scratch (this chapterβs exercise, LeetCode 146).
- Implement LFU Cache (LeetCode 460) β a strictly harder variant requiring frequency tracking alongside recency.
- Design a thread-safe version of LRU Cache (discuss locking strategy β a common systems-interview follow-up).
- All O(1) Data Structure (LeetCode 432) β a related βcombine hash map + linked list for O(1) everythingβ problem.
- Design an in-memory cache with TTL (time-to-live) expiration in addition to LRU eviction.
Follow-ups / interviewer traps:
- βWhat if two threads call get() and put() concurrently β what breaks?β (tests awareness that the naive implementation is not thread-safe; pointer relinking during a concurrent read can corrupt the list β expects discussion of locking, or a lock-free/sharded design)
- βHow would you make this cache distributed across multiple machines?β (tests systems-design thinking beyond the single-machine data structure β consistent hashing, distributed invalidation, etc.)
- βYour cache needs to support very large capacities β does the hash mapβs memory overhead matter?β (tests awareness of real memory costs: each entry needs a hash map slot AND a linked list node with two pointers, non-trivial overhead at scale)
13. Practice Problems
Medium
- LRU Cache (LeetCode 146) β this chapterβs direct exercise
- Design a HashMap with expiry (variants seen in real interview loops)
Hard
- LFU Cache (LeetCode 460)
- All O(1) Data Structure (LeetCode 432)
- Design In-Memory File System (related βcombine multiple structures for O(1)/efficient operationsβ design pattern)
Also recommended: implement this from scratch under a strict time limit (20-30 minutes) as a mock-interview exercise β LRU Cache is one of the most frequently asked data-structure-design questions at major tech companies specifically because it requires correctly combining two structures rather than just implementing one in isolation.
14. Common Mistakes
- Desynchronizing the hash map and linked list β any operation that updates one without correspondingly updating the other corrupts the cache silently (no crash, just wrong future behavior).
- Forgetting that a
gethit counts as a βuseβ and must reorder the list, not just return the value. - Off-by-one/dangling-pointer bugs during eviction β deleting a node before removing its hash map entry, or vice versa in the wrong order.
- Using a singly linked list and then struggling to remove an arbitrary node in O(1) β this is exactly the tail-deletion problem from Chapter 2, and itβs precisely why LRU Cache requires a doubly linked list.
- Not using dummy sentinels, then mishandling the edge cases of an empty cache or a cache with exactly one item.
- Checking cache size at the wrong point in
putβ must check before deciding whether eviction is needed, not after already inserting.
15. Summary
Key takeaways:
- This capstone chapter is the payoff for the entire guideβs structure: neither a Hash Map nor a Doubly Linked List alone can give O(1) for both βfind by keyβ and βreorder by recencyβ β combining them does, by using the hash map to store direct pointers into the linked list.
- Every operation reduces to two universal building blocks: detach a node, and re-insert it as most-recently-used.
- Dummy sentinel nodes eliminate special-case edge handling for empty/single-element states.
- LRU is the default cache eviction policy across virtually every layer of computing (OS memory, databases, CDNs, browsers) because temporal locality β recently used data tends to be used again soon β holds for most real workloads.
Complexity recap:
| Operation | Time | Space |
|---|---|---|
| get | O(1) | O(1) |
| put (any case, including eviction) | O(1) | O(1) |
| Overall | β | O(capacity) |
Decision guideline: Reach for this Hash Map + Doubly Linked List combination whenever you need O(1) lookup and O(1) reordering/removal by recency (or any other βmost recently touchedβ criterion) β not just for caching, but for any βbounded working set with fast evictionβ problem. If your eviction policy is frequency-based rather than recency-based, the same skeleton extends to LFU with additional bookkeeping (a frequency-bucketed structure, more involved but built on the same core idea).
Guide Complete β Final Reflection
Youβve now covered every structure in the original roadmap: Arrays β Strings-adjacent concepts woven throughout β Linked Lists β Stack/Queue β Hash Tables β Binary Tree/BST β AVL Tree β Trie β B-Tree β Graphs (representation, BFS, DFS, Topological Sort, MST, Shortest Path) β Segment Tree β Fenwick Tree β DSU β Skip List β Bloom Filter β LRU Cache.
The throughline worth carrying forward: almost every βadvancedβ structure in this guide is either (a) a clever index/pointer trick layered over an array or linked list, or (b) a combination of two simpler structures used together to cancel out each otherβs weaknesses (exactly like this capstone). When you encounter an unfamiliar data structure in the future, asking βwhat simpler structures is this built from, and what specific weakness is it patching?β will get you most of the way to understanding it β thatβs the same lens this entire guide has used, chapter after chapter.
Docker
Core Concepts
- Image: A lightweight, standalone, executable package. Itβs a blueprint that includes everything needed to run an application: code, runtime, system tools, and libraries.
- Container: A running instance of an image. Itβs the actual, isolated environment where your application runs. You can create, start, stop, and delete multiple containers from a single image.
- Docker Hub: A public registry (like GitHub for code) where you can find, share, and store container images.
- Dockerfile: A text file with instructions for building a Docker image.
Image Management (Build, Pull, List)
Commands for building, downloading, and managing your local images.
| Command | Description |
|---|---|
docker build -t <name:tag> . | Build an image from a Dockerfile in the current directory (.). The -t flag tags it with a human-readable name and tag (e.g., -t my-app:latest). |
docker build --no-cache ... | Build an image without using the cache. Use this to force a fresh build from scratch. |
docker pull <image_name> | Download (pull) an image from a registry like Docker Hub (e.g., docker pull postgres). |
docker images | List all images stored locally on your machine. |
docker rmi <image_name> | Remove (delete) a local image. You may need to stop/remove containers using it first. |
docker search <term> | Search Docker Hub for images matching a search term. |
Container Lifecycle (Run, Stop, Interact)
Commands for creating, running, and managing your containers.
| Command | Description |
|---|---|
docker run <image_name> | Create and start a new container from an image. |
docker run -d <image_name> | Run in detached mode (in the background). The terminal will be freed up. |
docker run --name <my-name> ... | Give your container a custom name (e.g., my-db-container). |
docker run -p 8080:80 ... | Map a port from your local machine (host) to the container. This example maps host port 8080 to container port 80. |
docker run -v /path/on/host:/path/in/container ... | Mount a volume to persist data. This links a host directory to a container directory. |
docker run --rm ... | Automatically remove the container when it stops. Excellent for temporary tasks and cleanup. |
docker run -it <image_name> sh | Run in interactive mode (-it). This opens a shell (sh or bash) inside the new container. |
docker exec -it <container_name> sh | Execute a command (like sh) inside an already running container. |
docker start <container_name> | Start a stopped container. |
docker stop <container_name> | Stop a running container gracefully. |
docker kill <container_name> | Force-stop a running container immediately. |
docker rm <container_name> | Remove a stopped container. |
docker rm -f <container_name> | Force-remove a container (even if itβs running). |
Inspection & Logs
Commands for checking the status, logs, and details of your containers.
| Command | Description |
|---|---|
docker ps | List all running containers. |
docker ps -a | List all containers (running and stopped). |
docker logs <container_name> | Show the logs (console output) of a container. |
docker logs -f <container_name> | Follow the logs in real-time (streams the live output). |
docker inspect <container_name> | Show detailed information (JSON) about a container, including its IP address, port mappings, and volumes. |
docker container stats | Show a live stream of resource usage (CPU, Memory, Network) for all running containers. |
Docker Hub & Registries
Commands for authenticating and sharing your custom images.
| Command | Description |
|---|---|
docker login | Log in to Docker Hub or another container registry. Youβll be prompted for your credentials. |
docker push <username>/<image_name> | Push (upload) your local image to Docker Hub. The image must be tagged with your username first (e.g., docker build -t myuser/my-app .). |
System Cleanup (QOL)
Essential commands for freeing up disk space.
| Command | Description |
|---|---|
docker container prune | Remove all stopped containers. |
docker image prune | Remove dangling images (images that arenβt tagged or used by any container). |
docker image prune -a | Remove all unused images (any image not used by at least one container). |
docker volume prune | Remove all unused volumes (volumes not attached to any container). |
docker system prune | The βbig oneβ: Removes all stopped containers, all dangling images, and all unused networks. |
docker system prune -a --volumes | The βnukeβ: Removes all stopped containers, all unused images (not just dangling), all unused networks, and all unused volumes. |
Docker Compose (Advanced)
The standard tool for defining and running multi-container applications (e.g., a web app, a database, and a cache). It uses a docker-compose.yml file.
| Command | Description |
|---|---|
docker compose up | Build and start all services defined in your docker-compose.yml file. Runs in the foreground. |
docker compose up -d | Build and start all services in detached mode (in the background). |
docker compose down | Stop and remove all containers, networks, and (by default) default volumes defined in the compose file. |
docker compose down -v | Stop and remove everything, including named volumes. |
docker compose ps | List all containers managed by the current compose project. |
docker compose logs | Show logs from all services in the compose project. |
docker compose logs -f <service_name> | Follow the logs in real-time for one or more specific services. |
docker compose exec <service_name> sh | Execute a command (like sh) inside a running serviceβs container. |
docker compose build | Force a rebuild of the images for your services before starting. |
Volumes & Networking (Advanced)
Commands for explicitly managing persistent data and custom networks.
| Command | Description |
|---|---|
docker volume ls | List all volumes on your system. |
docker volume create <volume_name> | Create a new managed volume. |
docker volume inspect <volume_name> | Show detailed information about a volume. |
docker volume rm <volume_name> | Remove one or more volumes. |
docker network ls | List all networks on your system. |
docker network create <network_name> | Create a new custom bridge network. Containers on the same network can communicate by name. |
docker network inspect <network_name> | Show detailed information about a network. |
docker network connect <net> <container> | Connect a running container to an additional network. |
Git
π Initial Configuration
Set these up once on any new machine.
git config --global user.name "Your Name"- Sets the name that will appear on your commits.
git config --global user.email "you@example.com"- Sets the email for your commits.
git config --global init.defaultBranch main- Sets the default branch name to
mainfor new repos.
- Sets the default branch name to
git config --global alias.lg "log --graph --oneline --decorate --all"- Creates a
git lgshortcut for a clean, comprehensive log.
- Creates a
git config --global alias.st "status -s"- Creates a
git stshortcut for a short, one-line status.
- Creates a
π¦ Basic Workflow: Staging & Committing
This is your day-to-day command cycle.
git init- Initializes a new Git repository in the current directory.
git status- Shows the status of your working directory and staging area (untracked, modified, and staged files).
git add <file...>- Adds one or more specific files to the staging area.
- Example:
git add README.md package.json
git add .- Adds all new and modified files in the current directory to the staging area.
git add -p- Interactively stages parts of files. Git will show you each βhunkβ of changes and ask if you want to stage it (y/n/q).
git commit -m "Your descriptive message"- Saves a permanent snapshot of the staged files to the project history.
git commit -am "Your message"- A shortcut to stage all tracked files and commit them in one step. (Note: Does not add new, untracked files).
git rm <file>- Removes a file from both the working directory and the staging area.
git rm --cached <file>- Removes a file from the staging area (index) but keeps the file in your working directory. Useful for βuntrackingβ a file, like a config file you accidentally added.
git mv <old-name> <new-name>- Renames a file. This is equivalent to
mv <old> <new>,git rm <old>, andgit add <new>.
- Renames a file. This is equivalent to
π Inspecting History & Logs
See what has happened in the project.
git log- Shows the full commit history for the current branch.
git log --oneline- Shows a compact, one-line view of the commit history.
git lg(orgit log --graph --oneline --decorate --all)- A powerful, customized log (using the alias from setup) that shows all branches, commit graphs, and tags in a clean one-line format.
git log -p <file>- Shows the commit history for a specific file, including the changes (patches) made in each commit.
git reflog- Shows a log of all movements of
HEAD(commits, checkouts, resets, merges). This is your ultimate safety net for finding βlostβ commits.
- Shows a log of all movements of
πΏ Branching & Merging
Manage parallel lines of development.
Branching
git branch- Lists all your local branches.
git branch -a- Lists all local and remote-tracking branches.
git branch <branch-name>- Creates a new branch based on your current
HEAD.
- Creates a new branch based on your current
git checkout <branch-name>- Switches your working directory to the specified branch.
git checkout -b <branch-name>- A shortcut to create a new branch and switch to it immediately.
git branch -m <new-name>- Renames the current branch.
git branch -d <branch-name>- Deletes a merged local branch. Git will stop you if the branch isnβt merged (safety feature).
git branch -D <branch-name>- Force deletes a local branch, even if itβs not merged.
Merging & Rebasing
git merge <branch-name>- Merges the specified branch into your current branch. This creates a new βmerge commitβ if there are new commits on both branches (a non-fast-forward merge).
git rebase <branch-name>- Re-applies your current branchβs commits on top of the specified branch. This creates a cleaner, linear history.
- Example: Youβre on
featureandmainhas updated. Rungit rebase mainto move yourfeaturework to the tip ofmain.
git rebase -i HEAD~3- Interactively rebase the last 3 commits. This opens an editor allowing you to
squash(combine),reword(change message),edit,drop, or reorder commits.
- Interactively rebase the last 3 commits. This opens an editor allowing you to
π₯ Stashing
Temporarily save changes you arenβt ready to commit.
git stashorgit stash save "Your message"- Takes all your uncommitted changes (in tracked files), saves them, and cleans your working directory back to
HEAD.
- Takes all your uncommitted changes (in tracked files), saves them, and cleans your working directory back to
git stash list- Shows all stashes youβve saved.
git stash pop- Applies the most recent stash to your working directory and deletes it from the stash list.
git stash apply <stash@{n}>- Applies a specific stash (e.g.,
stash@{1}) but does not delete it from the list.
- Applies a specific stash (e.g.,
git stash drop <stash@{n}>- Deletes a specific stash from the list.
π‘ Remote Repositories (e.g., GitHub)
Manage connections to other repositories.
Managing Remotes
git remote add <name> <url>- Adds a new remote. The standard name is
origin. - Example:
git remote add origin https://github.com/user/repo.git
- Adds a new remote. The standard name is
git remote -v- Lists all your remotes with their URLs.
git remote rename <old-name> <new-name>- Renames a remote.
git remote remove <name>- Removes a remote.
Syncing Changes
git fetch <remote-name>- Downloads all branches and history from the remote without merging them into your local branches. This is safe and lets you inspect changes first.
git pull <remote-name> <branch-name>- A shortcut for
git fetchfollowed bygit merge. It fetches and immediately tries to merge the remote branch into your current local branch. - Example:
git pull origin main
- A shortcut for
git push <remote-name> <branch-name>- Uploads your local branchβs commits to the remote repository.
git push -u <remote-name> <branch-name>- Pushes and sets the remote as the βupstreamβ tracking branch. After this, you can just run
git pullorgit pushfrom that branch.
- Pushes and sets the remote as the βupstreamβ tracking branch. After this, you can just run
git push <remote-name> --delete <branch-name>- Deletes a branch on the remote repository.
git push --force-with-lease- β οΈ Force-pushes your local branch, overwriting the remote. This is safer than
git push --forcebecause it will fail if someone else has pushed new commits in the meantime. Use this only when you have rewritten history (e.g., rebase) and have coordinated with your team.
- β οΈ Force-pushes your local branch, overwriting the remote. This is safer than
β©οΈ Undoing & Rewriting History
How to fix mistakes βafter the fact.β
Before Committing (Working Directory / Staging)
git restore <file>- Discards changes in your working directory. (The modern, clearer version of
git checkout -- <file>).
- Discards changes in your working directory. (The modern, clearer version of
git restore --staged <file>- Unstages a file, moving it from the staging area back to the working directory. (The modern version of
git reset HEAD <file>).
- Unstages a file, moving it from the staging area back to the working directory. (The modern version of
After Committing (But Before Pushing)
git commit --amend- Lets you change the last commitβs message or add more staged files to it. It replaces the last commit with a new one.
git reset --soft HEAD~1- Un-commits the last commit. The changes from that commit are moved to the staging area.
git reset --mixed HEAD~1(This is the default)- Un-commits the last commit. The changes are moved to the working directory (unstaged).
git reset --hard HEAD~1- β οΈ Destroys the last commit and all changes associated with it. Your working directory is reset to the state of the commit before it. This is permanent.
git reset --hard <commit-hash>- β οΈ Resets your entire project (working directory and index) to a specific commit. Discards all subsequent commits and changes.
After Pushing (Public Commits)
git revert <commit-hash>- The safe way to βundoβ a public commit. This creates a new commit that is the exact inverse of the specified commit. It doesnβt rewrite history.
git revert -m 1 <merge-commit-hash>- Reverts a merge commit.
-m 1tells Git which parent to keep (usually 1).
- Reverts a merge commit.
- Changing a Pushed Commit Message:
- This is highly disruptive to your team. Avoid if possible.
git rebase -i HEAD~5(Go back far enough to find the commit)- Find the commit line, change
picktoreword(orr). - Save and close. Git will prompt you to enter the new message.
git push --force-with-lease
- You must force-push because youβve rewritten public history. All collaborators will need to re-sync their branches.
π οΈ Advanced Tools
Git Worktrees
Manage multiple branches in separate directories simultaneously.
git clone --bare . /path/to/my-bare-repo.git- Clone the current repository as a bare repository
git worktree add <path> <branch-name>- Checks out a branch into a new directory. This is great for working on a hotfix while keeping your main
featurebranch checked out in your primary folder. - Example:
git worktree add ../my-hotfix-branch hotfix
- Checks out a branch into a new directory. This is great for working on a hotfix while keeping your main
git worktree list- Shows all active worktrees.
git worktree remove <path>- Removes the worktree at the specified path.
Git Submodules
Manage a repository inside another repository.
git submodule add <repo-url> <path>- Adds the other repo as a submodule in the specified path.
git clone --recurse-submodules <repo-url>- Clones a repository and automatically initializes and updates all its submodules.
git submodule update --init --recursive- Run this after a normal
git clone(orgit pull) to initialize or update submodules.
- Run this after a normal
- Workflow for updating a submodule:
cd <submodule-path>git checkout main(or desired branch)git pullcd ..(back to the parent repo)git add <submodule-path>git commit -m "Update submodule to latest"
- This βparentβ commit locks the submodule to the new commit hash you just pulled.
Relational
MySQL
MySQL Usage Guide
DATABASE
Creating, using, and managing databases.
-- Create a new database named myDB
CREATE DATABASE myDB;
-- Switch to the newly created database
USE myDB;
-- Delete the myDB database
DROP DATABASE myDB;
-- Set the myDB database to read-only mode
ALTER DATABASE myDB READ ONLY = 1;
-- Reset the read-only mode of the myDB database
ALTER DATABASE myDB READ ONLY = 0;
TABLES
Creating and modifying tables to organize data.
-- Create an 'employees' table with specified columns
CREATE TABLE employees(
employee_id INT,
first_name VARCHAR(50),
last_name VARCHAR(50),
hourly_pay DECIMAL(5, 2),
hire_date DATE
);
-- Retrieve all data from the 'employees' table
SELECT * FROM employees;
-- Rename the 'employees' table to 'workers'
RENAME TABLE employees TO workers;
-- Delete the 'employees' table
DROP TABLE employees;
Altering Tables
-- Add a new column 'phone_number' to the 'employees' table
ALTER TABLE employees
ADD phone_number VARCHAR(15);
-- Rename the 'phone_number' column to 'email'
ALTER TABLE employees
RENAME COLUMN phone_number TO email;
-- Change the data type of the 'email' column
ALTER TABLE employees
MODIFY COLUMN email VARCHAR(100);
-- Change the position of the 'email' column
ALTER TABLE employees
MODIFY email VARCHAR(100) AFTER last_name;
-- Move the 'email' column to the first position
ALTER TABLE employees
MODIFY email VARCHAR(100) FIRST;
-- Delete the 'email' column
ALTER TABLE employees
DROP COLUMN email;
INSERT ROW
Inserting data into tables.
-- Insert a single row into the 'employees' table
INSERT INTO employees VALUES(1, "Akib", "Ahmed", 25.90, "2024-04-06");
-- Insert multiple rows into the 'employees' table
INSERT INTO employees VALUES
(2, "Sakib", "Ahmed", 20.10, "2024-04-06"),
(3, "Rakib", "Ahmed", 16.40, "2024-04-06"),
(4, "Mula", "Ahmed", 10.90, "2024-04-06"),
(5, "Kodhu", "Ahmed", 19.70, "2024-04-06"),
(6, "Lula", "Ahmed", 23.09, "2024-04-06");
-- Insert specific fields into the 'employees' table
INSERT INTO employees (employee_id, first_name, last_name) VALUES(6, "Munia", "Khatun");
SELECT
Retrieving data from tables.
-- Retrieve all data from the 'employees' table
SELECT * FROM employees;
-- Retrieve specific fields from the 'employees' table
SELECT first_name, last_name FROM employees;
-- Retrieve data from the 'employees' table based on a condition
SELECT * FROM employees WHERE employee_id <= 2;
-- Retrieve data where the 'hire_date' column is NULL
SELECT * FROM employees WHERE hire_date IS NULL;
-- Retrieve data where the 'hire_date' column is not NULL
SELECT * FROM employees WHERE hire_date IS NOT NULL;
UPDATE & DELETE
Modifying and deleting data.
-- Update data in the 'employees' table based on a condition
UPDATE employees
SET hourly_pay = 10.3, hire_date = "2024-01-05"
WHERE employee_id = 7;
-- Update all rows in the 'employees' table for the 'hourly_pay' column
UPDATE employees
SET hourly_pay = 10.3;
-- Delete rows from the 'employees' table where 'hourly_pay' is NULL
DELETE FROM employees
WHERE hourly_pay IS NULL;
-- Delete the 'date_time' column from the 'employees' table
ALTER TABLE employees
DROP COLUMN date_time;
AUTO-COMMIT, COMMIT & ROLLBACK
Managing transactions.
-- Turn off auto-commit mode
SET AUTOCOMMIT = OFF;
-- Manually save changes made in the current transaction
COMMIT;
-- Delete all data from the 'employees' table
DELETE FROM employees;
-- Roll back changes made in the current transaction
ROLLBACK;
DATE & TIME
Working with date and time data.
-- Add a 'join_time' column to the 'employees' table
ALTER TABLE employees
ADD COLUMN join_time TIME;
-- Update the 'join_time' column with the current time
UPDATE employees
SET join_time = CURRENT_TIME();
-- Update the 'hire_date' column based on a condition
UPDATE employees
SET hire_date = CURRENT_DATE() + 1
WHERE hourly_pay >= 20;
-- Add a 'date_time' column to the 'employees' table
ALTER TABLE employees
ADD COLUMN date_time DATETIME;
-- Update the 'date_time' column with the current date and time
UPDATE employees
SET date_time = NOW();
-- Change the name of the 'hire_date' column to 'hire_date'
ALTER TABLE employees
CHANGE COLUMN hire_date hire_date DATE;
CONSTRAINTS
Ensuring data integrity with constraints.
UNIQUE
-- Create a 'products' table with a unique constraint on the 'product_name' column
CREATE TABLE products(
product_id INT,
product_name VARCHAR(50) UNIQUE,
product_price DECIMAL(4,2)
);
-- Add a unique constraint to the 'product_name' column in the 'products' table
ALTER TABLE products
ADD CONSTRAINT UNIQUE(product_name);
-- Insert data into the 'products' table
INSERT INTO products VALUES
(1, "tea", 15.9),
(2, "coffee", 20.89),
(3, "lemon", 10.10);
NOT NULL
-- Create a 'products' table with a NOT NULL constraint on the 'product_price' column
CREATE TABLE products(
product_id INT,
product_name VARCHAR(50) UNIQUE,
product_price DECIMAL(4,2) NOT NULL
);
-- Update the 'product_price' column to be NOT NULL
ALTER TABLE products
MODIFY product_price DECIMAL(4,2) NOT NULL;
-- Insert data into the 'products' table with a NOT NULL column
INSERT INTO products VALUES(4, "mango", 0);
CHECK
-- Create an 'employees' table with a check constraint on the 'hourly_pay' column
CREATE TABLE employees(
employee_id INT,
first_name VARCHAR(50),
last_name VARCHAR(50),
hourly_pay DECIMAL(5, 2),
hire_date DATE,
CONSTRAINT chk_hourly_pay CHECK (hourly_pay >= 10)
);
-- Add a check constraint to the 'hourly_pay' column
ALTER TABLE employees
ADD CONSTRAINT chk_hourly_pay CHECK(hourly_pay >= 10);
-- Insert data into the 'employees' table
INSERT INTO employees VALUES(7, "Kutta", "Mizan", 10.0, CURRENT_DATE(), CURRENT_TIME());
DEFAULT
-- Create a 'products' table with a default value for the 'product_price' column
CREATE TABLE products(
product_id INT,
product_name VARCHAR(50) UNIQUE,
product_price DECIMAL(4,2) DEFAULT 0
);
-- Set the default value for the 'product_price' column
ALTER TABLE products
ALTER product_price SET DEFAULT 0;
-- Insert data into the 'products' table with a default value
INSERT INTO products (product_id, product_name) VALUES(5, "soda");
-- Create a 'transactions' table with a default value for the 'transaction_date' column
CREATE TABLE transactions(
transaction_id INT,
amount DECIMAL(5,2),
transaction_date DATETIME DEFAULT NOW()
);
PRIMARY KEY
-- Create a table for transactions with a primary key
CREATE TABLE transactions(
transaction_id INT PRIMARY KEY,
amount DECIMAL(4,2),
transaction_date DATETIME
);
-- Add a primary key constraint
ALTER TABLE transactions
ADD CONSTRAINT PRIMARY KEY(transaction_id);
-- Set auto-increment for the primary key
ALTER TABLE transactions AUTO_INCREMENT = 1000;
-- Insert data into the transactions table
INSERT INTO transactions(amount) VALUES (54.20);
-- Select all data from the transactions table
SELECT * FROM transactions;
AUTO_INCREMENT
-- Create a table for transactions with an auto-increment primary key
CREATE TABLE transactions(
transaction_id INT PRIMARY KEY AUTO_INCREMENT,
amount DECIMAL(5,2),
transaction_date DATETIME DEFAULT NOW()
);
-- Set the default increment level
ALTER TABLE transactions AUTO_INCREMENT = 1000;
-- Insert data into the transactions table, auto-increment starts from 1000
INSERT INTO transactions(amount) VALUES (45.20), (23.40), (98.00), (43.45);
-- Select all data from the transactions table
SELECT * FROM transactions;
FOREIGN KEY
-- Create a table for customers with a primary key
CREATE TABLE customers(
customer_id INT PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(50),
last_name VARCHAR(50)
);
-- Create a table for
transactions with a foreign key constraint
CREATE TABLE transactions(
transaction_id INT PRIMARY KEY AUTO_INCREMENT,
amount DECIMAL(5,2),
transaction_date DATETIME DEFAULT NOW(),
customer_id INT,
FOREIGN KEY(customer_id) REFERENCES customers(customer_id)
);
-- Add a foreign key constraint to the transactions table
ALTER TABLE transactions
ADD CONSTRAINT fk_customer_key
FOREIGN KEY(customer_id) REFERENCES customers(customer_id);
-- Insert data into the transactions table with customer_id
INSERT INTO transactions(amount, customer_id) VALUES (34.34, 1), (123.4, 3), (32.32, 1), (12.00, 2);
JOIN
Combining data from multiple tables.
-- Inner join transactions and customers tables
SELECT *
FROM transactions
INNER JOIN customers
ON transactions.customer_id = customers.customer_id;
-- Select specific fields from joined tables
SELECT transaction_id, transaction_date, first_name, last_name
FROM transactions
INNER JOIN customers
ON transactions.customer_id = customers.customer_id;
-- Left join transactions and customers tables
SELECT *
FROM transactions
LEFT JOIN customers
ON transactions.customer_id = customers.customer_id;
-- Right join transactions and customers tables
SELECT *
FROM transactions
RIGHT JOIN customers
ON transactions.customer_id = customers.customer_id;
FUNCTIONS
Built-in SQL functions.
-- Count the number of transactions
SELECT COUNT(amount) AS "Transaction count" FROM transactions;
-- Find the maximum amount
SELECT MAX(amount) AS max_dollar FROM transactions;
-- Find the minimum amount
SELECT MIN(amount) AS min_dollar FROM transactions;
-- Find the average amount
SELECT AVG(amount) AS avg_dollar FROM transactions;
-- Calculate the total amount
SELECT SUM(amount) AS sum_of_dollar FROM transactions;
-- Concatenate first_name and last_name into a new column
SELECT CONCAT(first_name, " ", last_name) as full_name FROM customers;
AND, OR & NOT
Combining conditions in SQL queries.
-- Add a job column to the employees table
ALTER TABLE employees
ADD COLUMN job VARCHAR(50) AFTER hourly_pay;
-- Update job data based on employee_id
UPDATE employees
SET job = "Programmer"
WHERE employee_id = 1;
-- Select employees with specific conditions
SELECT * FROM employees
WHERE employee_id >= 2 AND employee_id <= 6 AND job = "vendor";
-- Select employees with specific conditions using OR
SELECT * FROM employees
WHERE job = "programmer" OR job = "vendor";
-- Select employees with specific conditions using NOT
SELECT * FROM employees
WHERE NOT job = "programmer" AND NOT job = "vendor";
-- Select employees within a certain hourly pay range
SELECT * FROM employees
WHERE hourly_pay BETWEEN 15 AND 26;
-- Select employees with specific jobs using IN
SELECT * FROM employees
WHERE job IN("programmer", "vendor", "doctor");
WILD-CARDS
Using wildcards for pattern matching.
-- Select employees with first name ending with "hu"
SELECT * FROM employees
WHERE first_name LIKE "%hu";
-- Select employees hired on a specific day (07)
SELECT * FROM employees
WHERE hire_date LIKE "____-__-07";
-- Select employees with job ending with "e" followed by another character
SELECT * FROM employees
WHERE job LIKE "%e_";
ORDER BY
Sorting query results.
-- Select employees ordered by hourly pay in ascending order
SELECT * FROM employees
ORDER BY hourly_pay ASC;
-- Select employees ordered by hire date in descending order
SELECT * FROM employees
ORDER BY hire_date DESC;
-- Select transactions ordered by amount in descending order and customer_id in ascending order
SELECT * FROM transactions
ORDER BY amount DESC, customer_id ASC;
LIMIT
Limiting the number of records returned.
-- Select the first 3 customers
SELECT * FROM customers
LIMIT 3;
-- Select the last 3 customers ordered by customer_id
SELECT * FROM customers
ORDER BY customer_id DESC LIMIT 3;
-- Select 2 customers starting from the 1st position (pagination)
SELECT * FROM customers
LIMIT 0,2;
UNION
Combining results from multiple SELECT statements.
-- Combine unique first and last names from employees and customers
SELECT first_name, last_name FROM employees
UNION
SELECT first_name, last_name FROM customers;
-- Combine all first and last names from employees and customers, including duplicates
SELECT first_name, last_name FROM employees
UNION ALL
SELECT first_name, last_name FROM customers;
SELF JOIN
Joining a table to itself.
-- Add a referral_id column to the customers table
ALTER TABLE customers
ADD COLUMN referral_id INT;
-- Update referral_id for customers
UPDATE customers
SET referral_id = 1
WHERE customer_id = 2;
-- Self join to show referred customers
SELECT a.customer_id, a.first_name, a.last_name,
CONCAT(b.first_name, " ", b.last_name) AS "referred_by"
FROM customers AS a
INNER JOIN customers AS b
ON a.referral_id = b.customer_id;
-- Add a supervisor_id column to the employees table
ALTER TABLE employees
ADD supervisor_id INT;
-- Update supervisor_id for employees
UPDATE employees
SET supervisor_id = 7
WHERE employee_id BETWEEN 2 and 6;
-- Update supervisor_id for a specific employee
UPDATE employees
SET supervisor_id = 1
WHERE employee_id = 7;
-- Self join to show employees and their supervisors
SELECT a.employee_id, a.first_name, a.last_name,
CONCAT(b.first_name, " ", b.last_name) AS "reports to"
FROM employees AS a
INNER JOIN employees AS b
ON a.supervisor_id = b.employee_id;
VIEWS
Creating and using virtual tables.
-- Create a view based on the employees table
CREATE VIEW employee_attendance AS
SELECT first_name, last_name
FROM employees;
-- Retrieve data from the view
SELECT * FROM employee_attendance
ORDER BY last_name ASC;
-- Create a view for customer emails
CREATE VIEW customer_emails AS
SELECT email
FROM customers;
-- Insert data into the customers table and view the changes in the view
INSERT INTO customers
VALUES(6, "Musa", "Rahman", NULL, "musa@mail.com");
SELECT * FROM customers;
SELECT * FROM customer_emails;
INDEX
Improving query performance with indexes.
-- Show indexes for the customers table
SHOW INDEXES FROM customers;
-- Create an index on the last_name column
CREATE INDEX last_name_index
ON customers(last_name);
-- Use the index to speed up search
SELECT * FROM customers
WHERE last_name = "Chan";
-- Create a multi-column index
CREATE INDEX last_name_first_name_idx
ON customers(last_name, first_name);
-- Drop an index
ALTER TABLE customers
DROP INDEX last_name_index;
-- Benefit from the multi-column index during search
SELECT * FROM customers
WHERE last_name = "Chan" AND first_name = "Kuki";
SUB-QUERY
Using sub-queries to nest queries within queries.
-- Get the average hourly pay
SELECT AVG(hourly_pay) FROM employees;
-- Use a sub-query to get the average hourly pay within a larger query
SELECT first_name, last_name, hourly_pay,
(SELECT AVG(hourly_pay) FROM employees) AS avg_hourly_pay
FROM employees;
-- Filter rows based on a sub-query result
SELECT first_name, last_name, hourly_pay
FROM employees
WHERE hourly_pay >= (SELECT AVG(hourly_pay) FROM employees);
-- Use a sub-query with IN to filter customers
SELECT first_name, last_name
FROM customers
WHERE customer_id IN (SELECT DISTINCT customer_id
FROM transactions
WHERE customer_id IS NOT NULL);
-- Use a sub-query with NOT IN to filter customers
SELECT first_name, last_name
FROM customers
WHERE customer_id NOT IN (SELECT DISTINCT customer_id
FROM transactions
WHERE customer_id IS NOT NULL);
GROUP BY
Aggregating data with grouping.
-- Sum amounts grouped by transaction date
SELECT SUM(amount), transaction_date
FROM transactions
GROUP BY transaction_date;
-- Get the maximum amount per customer
SELECT MAX(amount), customer_id
FROM transactions
GROUP BY customer_id;
-- Count transactions per customer having more than one transaction
SELECT COUNT(amount), customer_id
FROM transactions
GROUP BY customer_id
HAVING COUNT(amount) > 1 AND customer_id IS NOT NULL;
ROLL-UP
Extending group by with roll-up for super-aggregate values.
-- Sum amounts with a roll-up
SELECT SUM(amount), transaction_date
FROM transactions
GROUP BY transaction_date WITH ROLLUP;
-- Count transactions with a roll-up
SELECT COUNT(transaction_id) AS "# of orders", customer_id
FROM transactions
GROUP BY customer_id WITH ROLLUP;
-- Sum hourly pay with a roll-up
SELECT SUM(hourly_pay) AS "hourly pay", employee_id
FROM employees
GROUP BY employee_id WITH ROLLUP;
ON-DELETE
Handling foreign key deletions.
-- Delete a customer record
DELETE FROM customers
WHERE customer_id = 3;
-- Disable foreign key checks and delete a customer
SET foreign_key_checks = 0;
DELETE FROM customers
WHERE customer_id = 3;
SET foreign_key_checks = 1;
-- Insert a customer record
INSERT INTO customers
VALUES(3, "Shilpi", "Akter", 3, "shilpy@mail.com");
-- Create a table with ON DELETE SET NULL
CREATE TABLE transactions(
transaction_id INT PRIMARY KEY,
amount DECIMAL(5,
3),
customer_id INT,
order_date DATE,
FOREIGN KEY(customer_id) REFERENCES customers(customer_id)
ON DELETE SET NULL
);
-- Update an existing table with ON DELETE SET NULL
ALTER TABLE transactions
DROP FOREIGN KEY fk_customer_key;
ALTER TABLE transactions
ADD CONSTRAINT fk_customer_key
FOREIGN KEY(customer_id) REFERENCES customers(customer_id)
ON DELETE SET NULL;
-- Create or alter a table with ON DELETE CASCADE
ALTER TABLE transactions
ADD CONSTRAINT fk_transaction_id
FOREIGN KEY(customer_id) REFERENCES customers(customer_id)
ON DELETE CASCADE;
STORED PROCEDURE
Creating reusable SQL code blocks.
-- Create a procedure
DELIMITER $$
CREATE PROCEDURE get_customers()
BEGIN
SELECT * FROM customers;
END $$
DELIMITER ;
-- Delete a procedure
DROP PROCEDURE get_customers;
-- Create a procedure with an argument
DELIMITER $$
CREATE PROCEDURE find_customer(IN id INT)
BEGIN
SELECT * FROM customers WHERE customer_id = id;
END $$
DELIMITER ;
-- Create a procedure with multiple arguments
DELIMITER $$
CREATE PROCEDURE find_customer(IN f_name VARCHAR(50), IN l_name VARCHAR(50))
BEGIN
SELECT * FROM customers WHERE first_name = f_name AND last_name = l_name;
END $$
DELIMITER ;
-- Call a procedure
CALL find_customer("Akib", "Ahmed");
TRIGGERS
Automatically performing actions in response to events.
-- Add a salary column to the employees table
ALTER TABLE employees
ADD COLUMN salary DECIMAL(10,2) AFTER hourly_pay;
-- Calculate salary based on hourly pay
UPDATE employees
SET salary = hourly_pay * 2080;
-- Create a trigger to update salary before updating hourly pay
CREATE TRIGGER before_hourly_pay_update
BEFORE UPDATE ON employees
FOR EACH ROW
SET NEW.salary = (NEW.hourly_pay * 2080);
-- Update hourly pay and see the trigger in action
UPDATE employees
SET hourly_pay = 50
WHERE employee_id = 1;
-- Create a trigger to update salary before inserting a new employee
CREATE TRIGGER before_hourly_pay_insert
BEFORE INSERT ON employees
FOR EACH ROW
SET NEW.salary = (NEW.hourly_pay * 2080);
-- Insert a new employee and see the trigger in action
INSERT INTO employees
VALUES(6, "Shel", "Plankton", 10, NULL, "Janitor", "2024-06-17", "09:22:23", 7);
-- Create a table for expenses
CREATE TABLE expenses(
expense_id INT PRIMARY KEY,
expense_name VARCHAR(50),
expense_total DECIMAL(10,2)
);
-- Insert initial data into the expenses table
INSERT INTO expenses
VALUES (1, "salaries", 0), (2, "supplies", 0), (3, "taxes", 0);
-- Update expenses based on salaries
UPDATE expenses
SET expense_total = (SELECT SUM(salary) FROM employees)
WHERE expense_name = "salaries";
-- Create a trigger to update expenses after deleting an employee
CREATE TRIGGER after_salary_delete
AFTER DELETE ON employees
FOR EACH ROW
UPDATE expenses
SET expense_total = expense_total - OLD.salary
WHERE expense_name = "salaries";
-- Delete an employee and see the trigger in action
DELETE FROM employees
WHERE employee_id = 6;
-- Create a trigger to update expenses after inserting a new employee
CREATE TRIGGER after_salary_insert
AFTER INSERT ON employees
FOR EACH ROW
UPDATE expenses
SET expense_total = expense_total + NEW.salary
WHERE expense_name = "salaries";
-- Insert a new employee and see the trigger in action
INSERT INTO employees
VALUES(6, "Shel", "Plankton", 10, NULL, "Janitor", "2024-06-17", "09:22:23", 7);
-- Create a trigger to update expenses after updating an employee's salary
CREATE TRIGGER after_salary_update
AFTER UPDATE ON employees
FOR EACH ROW
UPDATE expenses
SET expense_total = expense_total + (NEW.salary - OLD.salary)
WHERE expense_name = "salaries";
-- Update an employee's hourly pay and see the trigger in action
UPDATE employees
SET hourly_pay = 100
WHERE employee_id = 1;
PostgreSQL
PostgreSQL Quick Guide
A concise guide to common PostgreSQL commands, syntax, and concepts.
Key Differences from MySQL:
- Strings: Use single quotes only (e.g.,
'Hello World'). - Identifiers: (Table/column names) are case-insensitive unless you wrap them in double quotes (e.g.,
"myColumn"). - Switching DBs: There is no
USE db_name;command. In thepsqlterminal, use the\c db_namemeta-command. - Auto-Increment: Use the
SERIALorGENERATED AS IDENTITYkeyword. - Concatenation: The standard SQL
||operator is preferred (e.g.,first_name || ' ' || last_name).
psql Command Line Basics
psql is the interactive terminal for PostgreSQL.
Connecting:
# Connect to a specific database as a specific user
psql -d myDB -U myUser -h localhost
Common Meta-Commands (start with \):
\l: List all databases.\c db_name: Connect to a different database.\dt: List all tables in the current database.\d table_name: Describe a table (columns, indexes, constraints).\dn: List all schemas.\df: List all functions.\du: List all users (roles).\timing: Toggles query execution time display.\e: Open the last query in your text editor.\q: Quitpsql.
Database & Role Management
Manage databases and user permissions.
-- Create a new database
CREATE DATABASE myDB;
-- Delete a database
DROP DATABASE myDB;
-- Create a new user (role) with login permission
CREATE ROLE myUser WITH LOGIN PASSWORD 'my_password';
-- Grant privileges for a user on a table
GRANT ALL ON employees TO myUser;
-- Grant privileges to connect to a database
GRANT CONNECT ON DATABASE myDB TO myUser;
Tables & Data Types
Create, modify, and delete tables.
-- Create a table with common data types
CREATE TABLE employees (
employee_id SERIAL PRIMARY KEY, -- Auto-incrementing primary key
first_name VARCHAR(50) NOT NULL,
hourly_pay NUMERIC(5, 2) DEFAULT 10.00, -- Equivalent to DECIMAL
hire_date DATE DEFAULT CURRENT_DATE,
created_at TIMESTAMP DEFAULT NOW()
);
-- Modify an existing table
ALTER TABLE employees
ADD COLUMN email VARCHAR(100) UNIQUE,
RENAME COLUMN hire_date TO joined_date,
ALTER COLUMN hourly_pay TYPE NUMERIC(6, 2),
DROP COLUMN some_old_column;
-- Rename a table
ALTER TABLE employees RENAME TO workers;
-- Delete a table
DROP TABLE employees;
Note: PostgreSQL does not support reordering columns (like AFTER or FIRST). You must recreate the table.
Constraints
Rules to ensure data integrity, best defined at creation.
CREATE TABLE products (
product_id SERIAL PRIMARY KEY,
product_name VARCHAR(50) UNIQUE NOT NULL,
price NUMERIC(6, 2) DEFAULT 0,
category_id INT,
-- Check constraint
CONSTRAINT chk_price CHECK (price >= 0),
-- Foreign key constraint with actions
CONSTRAINT fk_category
FOREIGN KEY(category_id)
REFERENCES categories(category_id)
ON DELETE SET NULL -- or ON DELETE CASCADE
);
-- Add a constraint to an existing table
ALTER TABLE employees
ADD CONSTRAINT chk_hourly_pay CHECK(hourly_pay >= 10.00);
Manipulating Data (CRUD)
The four basic data operations: Create, Read, Update, Delete.
-- CREATE (Insert)
-- Insert a single row (best practice to name columns)
INSERT INTO employees (first_name, last_name, hourly_pay)
VALUES ('Akib', 'Ahmed', 25.90);
-- Insert multiple rows
INSERT INTO employees (first_name, last_name, hourly_pay) VALUES
('Sakib', 'Ahmed', 20.10),
('Rakib', 'Ahmed', 16.40);
-- READ (Select)
SELECT * FROM employees;
-- UPDATE (Update)
UPDATE employees
SET hourly_pay = 27.50, email = 'akib@mail.com'
WHERE employee_id = 1;
-- DELETE (Delete)
DELETE FROM employees
WHERE employee_id = 1;
Transactions
Ensure that a group of SQL statements either all succeed or all fail together.
-- Start a transaction block
BEGIN;
-- Make changes
UPDATE employees SET hourly_pay = 99.00 WHERE employee_id = 2;
DELETE FROM employees WHERE employee_id = 3;
-- To undo the changes in this block
ROLLBACK;
-- To make the changes permanent
COMMIT;
Querying: Filtering & Sorting
Use SELECT to retrieve data with complex conditions.
SELECT
first_name || ' ' || last_name AS full_name,
hourly_pay,
joined_date
FROM employees
WHERE
(hourly_pay > 20 OR job IS NULL)
AND first_name ILIKE 'a%' -- ILIKE is case-insensitive LIKE
ORDER BY
joined_date DESC,
first_name ASC
LIMIT 10 OFFSET 5; -- Skip 5 rows, fetch the next 10 (for pagination)
Querying: Aggregation
Summarize data using aggregate functions and GROUP BY.
SELECT
job,
COUNT(employee_id) AS "employee_count",
AVG(hourly_pay) AS avg_pay,
SUM(hourly_pay) AS total_payroll
FROM employees
WHERE joined_date > '2023-01-01'
GROUP BY job
HAVING COUNT(employee_id) > 2 -- Filter groups, not rows
ORDER BY avg_pay DESC;
-- Use ROLLUP to get a grand total row
SELECT job, SUM(hourly_pay)
FROM employees
GROUP BY ROLLUP(job); -- Will add a final row with the total sum
Querying: Joins
Combine rows from two or more tables.
-- INNER JOIN: Returns only matching rows from both tables
SELECT e.first_name, t.amount
FROM employees AS e
INNER JOIN transactions AS t ON e.employee_id = t.employee_id;
-- LEFT JOIN: Returns all rows from the left (employees) table,
-- and matching rows from the right (transactions) table.
SELECT e.first_name, t.amount
FROM employees AS e
LEFT JOIN transactions AS t ON e.employee_id = t.employee_id;
-- SELF JOIN: Join a table to itself
SELECT a.first_name AS employee, b.first_name AS supervisor
FROM employees AS a
LEFT JOIN employees AS b ON a.supervisor_id = b.employee_id;
Querying: Combining
Combine the results of multiple SELECT statements.
-- UNION: Combines results and removes duplicates
SELECT first_name, last_name FROM employees
UNION
SELECT first_name, last_name FROM customers;
-- UNION ALL: Combines results and keeps all duplicates
SELECT first_name, last_name FROM employees
UNION ALL
SELECT first_name, last_name FROM customers;
-- Sub-query: Use a query result as a condition
SELECT * FROM employees
WHERE hourly_pay > (SELECT AVG(hourly_pay) FROM employees);
-- Common Table Expression (CTE): A temporary, named result set
WITH highest_payers AS (
SELECT * FROM employees WHERE hourly_pay > 50
)
SELECT * FROM highest_payers WHERE joined_date < '2024-01-01';
Database Objects
Reusable SQL components.
Views
A virtual table based on a SELECT query.
-- Create a read-only view
CREATE VIEW v_high_earners AS
SELECT employee_id, first_name, hourly_pay
FROM employees
WHERE hourly_pay > 30;
-- Query the view like a table
SELECT * FROM v_high_earners;
Indexes
Speed up data retrieval on frequently queried columns.
-- Create an index
CREATE INDEX idx_employees_last_name
ON employees(last_name);
-- Create a multi-column index
CREATE INDEX idx_employees_name
ON employees(last_name, first_name);
-- Drop an index
DROP INDEX idx_employees_last_name;
Stored Functions
Reusable blocks of code. In Postgres, these are typically functions that return a value or a table.
-- Create a function in the plpgsql language
CREATE OR REPLACE FUNCTION find_employee_by_id(id INT)
RETURNS SETOF employees AS $$
BEGIN
RETURN QUERY
SELECT * FROM employees WHERE employee_id = id;
END;
$$ LANGUAGE plpgsql;
-- Call the function
SELECT * FROM find_employee_by_id(1);
Triggers
A function that automatically runs when an event (INSERT, UPDATE, DELETE) occurs on a table.
This is a two-step process:
-- 1. Create the trigger FUNCTION
CREATE OR REPLACE FUNCTION log_last_update()
RETURNS TRIGGER AS $$
BEGIN
-- NEW refers to the row being inserted or updated
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- 2. Bind the function to a table with a TRIGGER
CREATE TRIGGER trg_employees_update
BEFORE UPDATE ON employees
FOR EACH ROW
EXECUTE FUNCTION log_last_update();
Advanced Features
JSONB
Store and query JSON data efficiently.
CREATE TABLE products (id SERIAL, data JSONB);
INSERT INTO products (data)
VALUES ('{"name": "Coffee", "tags": ["hot", "drink"]}');
-- Query a JSON key (->> returns as text)
SELECT * FROM products WHERE data->>'name' = 'Coffee';
-- Check if a JSON array contains a value
SELECT * FROM products WHERE data @> '{"tags": ["hot"]}';
Window Functions
Perform aggregate calculations over a βwindowβ of rows without collapsing them.
-- Get each employee's salary AND the average salary for their job
SELECT
first_name,
job,
hourly_pay,
AVG(hourly_pay) OVER (PARTITION BY job) AS avg_job_pay,
RANK() OVER (ORDER BY hourly_pay DESC) AS pay_rank
FROM employees;
Web_App
Linux Server Setup & MERN App Deployment
These are the steps to setup an Ubuntu server from scratch and deploy a MERN app with the PM2 process manager and Nginx. We are using Linode, but you could just as well use a different cloud provider or your own machine or VM.
Create an account at Linode
Click on Create Linode
Choose your server options (OS, region, etc)
SSH Keys
You will see on the setup page an area to add an SSH key.
There are a few ways that you can log into your server. You can use passwords, however, if you want to be more secure, I would suggest setting up SSH keys and then disabling passwords. That way you can only log in to your server from a PC that has the correct keys setup.
I am going to show you how to setup authentication with SSH, but if you want to just use a password, you can skip most of this stuff.
You need to generate an SSH key on your local machine to login to your server remotely. Open your terminal and type
ssh-keygen
By default, it will create your public and private key files in the .ssh directory on your local machine and name them id_rsa and id_rsa.pub. You can change this if you want, just make sure when it asks, you put the entire path to the key as well as the filename. I am using id_rsa_linode
Once you do that, you need to copy the public key. You can use the cat command and then copy the key
cat ~/.ssh/id_rsa_linode.pub
Copy the key. It will look something like this:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDEwMkP0KHX19q2dM/9pB9dpB2B/FwdeP4egXCgdEOraJuqGvaylKgbu7XDFinP6ByqJQg/w8vRV0CsFXrnr+Lh51fKv8ZPvV/yRIMjxKzNn/0+asatkjrkOwT3f3ipbzfS0bsqfWTHivZ7UNMrOHaaSezxvJpPGbW3aoTCFSA/sUUUSiWZ65v7I/tFkXE0XH+kSDFbLUDDNS1EzofWZFRcdSFbC3zrGsQHN3jcit6ba7bACQYixxFCgVB0mZO9SOgFHC64PEnZh5hJ8h8AqIjf5hDF9qFdz2jFEe/4aQmKQAD3xAPKTXDLLngV/2yFF0iWpnJ9MZ/mJoLVzhY2pfkKgnt/SUe/Hn1+jhX4wrz7wTDV4xAe35pmnajFjDppJApty+JOzKf3ifr4lNeZ5A99t9Pu0294BhYxm7/mKXiWPsevX9oSZxSJmQUtqWWz/KBVoVjlTRgAgLYbKCNBzmw7+qdRxoxxscQCQrCpJMlat56vxK8cjqiESvduUu78HHE= trave@ASUS
Now paste that into the Linode.com textarea and name it (eg.My PC)
At some point, you will be asked to enter a root password for your server as well.
Connecting as Root
Finish the setup and then you will be taken to your dashboard. The status will probably say Provisioning. Wait until it says Running and then open your local machineβs terminal and connect as root. Of course you want to use your own serverβs IP address
ssh root@69.164.222.31
At this point, passwords are enabled, so you will be asked for your root password.
If you authenticate and login, you should see a welcome message and your prompt should now say root@localhost:~#. This is your remote server
I usually suggest updating and upgrading your packages
sudo apt update
sudo apt upgrade
Create a new user
Right now you are logged in as root and it is a good idea to create a new account. Using the root account can be a security risk.
You can check your current user with the command:
whoami
It will say root right noe.
Letβs add a new user. I am going to call my user brad
adduser brad
Just hit enter through all the questions. You will be asked for a use password as well.
You can use the following command to see the user info including the groups it belongs to
id brad
Now, letβs add this user to the βsudoβ group, which will give them root privileges.
usermod -aG sudo brad
Now if you run the following command, you should see sudo
id brad
Add SSH keys for new account
If you are using SSH, you will want to setup SSH keys for the new account. We do this by adding it to a file called authorized_keys in the users directory.
Go to the new users home directory
cd /home/brad
Create a .ssh directory and go into it
mkdir .ssh
cd .ssh
Create a new file called authorized_keys
touch authorized_keys
Now you want to put your public key in that file. You can open it with a simpl text editor called nano
sudo nano authorized_keys
Now you can paste your key in here. Just repeat the step above where we ran cat and then the location of your public key. IMPORTANT: Make sure you open a new terminal for this that is not logged into your server.
Now paste the key in the file and hi ctrl or cmd+X then hit Y to save and hit enter again
Disabling passwords
This is an extra security step. Like I said earlier, we can disable passwords so that only your local machine with the correct SSH keys can login.
Open the following file on your server
sudo nano /etc/ssh/sshd_config
Look for where it says
PasswordAuthentication Yes
Remove the # if there is one and change the Yes to No
If you want to disable root login all together you could change permitRootLogin to no as well. Be sure to remove the # sign becayse that comments the line out.
Save the file by exiting (ctrl+x) and hit Y to save.
Now you need to reset the sshd service
sudo systemctl restart sshd
Now you can logout by just typing logout
Try logging back in with your user (Use your username and serverβs IP)
ssh brad@69.164.222.31
If you get a message that says βPublick key deniedβ or something like that, run the following commands:
eval `ssh-agent -s`
ssh-add ~/.ssh/id_rsa_linode # replace this with whatever you called your key file
try logging in again and you should see the welcome message and not have to type in any password.
Node.js setup
Now that we have provisioned our server and we have a user setup with SSH keys, itβs time to start setting up our app environment. Letβs start by installing Node.js
We can install Node.js with curl using the following commands
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
# Check to see if node was installed
node --version
npm --version
Get files on the server
We want to get our application files onto the server. We will use Git for this. I am using the goal setter app from my MERN stack series on YouTube
On your SERVER, go to where you want the app to live and clone the repo you want to deply from GitHub (or where ever else)
Here is the repo I will be using. Feel free to deploy the same app: https://github.com/bradtraversy/mern-tutorial
mkdir sites
cd sites
git clone https://github.com/bradtraversy/mern-tutorial.git
Now I should have a folder called mern-tutorial with all of my files and folders.
App setup
There are a few things that we need to do including setting up the .ENV file, installing dependencies and building our static assets for React.
.env file
With this particular application, I create a .envexample file because I did not want to push the actual .env file to GitHub. So you need to first rename that .envexample:
mv .envexample .env
# To check
ls -a
Now we need to edit that file
sudo nano .env
Change the NODE_ENV to βproductionβ and change the MONGO_URI to your own. You can create a mongodb Atlas database here
Exit with saving.
Dependencies & Build
We need to install the server dependencies. This should be run from the root of the mern-tutorial folder. NOT the backend folder.
npm install
Install frontend deps:
cd frontend
npm install
We need to build our static assets as well. Do this from the frontend folder
npm run build
Run the app
Now we should be able to run the app like we do on our local machine. Go into the root and run
npm start
If you go to your ip and port 5000, you should see your app. In my case, I would go to
http://69.164.222.31:5000
Even though we see our app running, we are not done. We donβt want to leave a terminal open with npm start. We also donβt want to have to go to port 5000. So letβs fix that.
Stop the app from running with ctrl+C
PM2 Setup
PM2 is a production process manager fro Node.js. It allows us to keep Node apps running without having to have terminal open with npm start, etc like we do for development.
Letβs first install PM2 globally with NPM
sudo npm install -g pm2
Run with PM2
pm2 start backend/server.js # or whatever your entry file is
Now if you go back to your server IP and port 5000, you will see it running. You could even close your terminal and it will still be running
There are other pm2 commands for various tasks as well that are pretty self explanatory:
- pm2 show app
- pm2 status
- pm2 restart app
- pm2 stop app
- pm2 logs (Show log stream)
- pm2 flush (Clear logs)
Firewall Setup
Obviously we donβt want users to have to enter a port of 5000 or anything else. We are going to solve that by using a server called NGINX. Before we set that up, lets setup a firewall so that people can not directly access any port except ports for ssh, http and https
The firewall we are using is called UFW. Letβs enable it.
sudo ufw enable
You will notice now if you go to the site using :5000, it will not work. That is because we setup a firewall to block all ports.
You can check the status of the firewall with
sudo ufw status
Now letβs open the ports that we need which are 22, 80 and 443
sudo ufw allow ssh (Port 22)
sudo ufw allow http (Port 80)
sudo ufw allow https (Port 443)
Setup NGINX
Now we need to install NGINX to serve our app on port 80, which is the http port
sudo apt install nginx
If you visit your IP address with no port number, you will see a Welcome to nginx! page.
Now we need to configure a proxy for our MERN app.
Open the following config file
sudo nano /etc/nginx/sites-available/default
Find the location / area and replace with this
location / {
proxy_pass http://localhost:5000; # or which other port your app runs on
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
Above that, you can also put the domain that you plan on using:
server_name yourdomain.com www.yourdomain.com;
Save and close the file
You can check your nginx configuration with the following command
sudo nginx -t
Now restart the NGINX service:
sudo service nginx restart
Now you should see your app when you go to your IP address in the browser.
Domain Name
You probably donβt want to use your IP address to access your app in the browser. So letβs go over setting your domain with a Linode.
You need to register your domain. It doesnβt matter who you use for a registrar. I use Namecheap, but you could use Godaddy, Google Domains or anyone else.
You need to change the nameservers with your Domain registrar. The process can vary depending on who you use. With Namecheap, the option is right on the details page.
You want to add the following nameservers:
- ns1.linode.com
- ns2.linode.com
- ns3.linode.com
- ns4.linode.com
- ns5.linode.com
Technically this could take up to 48 hours, but it almost never takes that long. In my own experience, it is usually 30 - 90 minutes.
Set your domain in Linode
Go to your dashboard and select Domains and then Create Domain
Add in your domain name and link to the Linode with your app, then submit the form.
Now you will see some info like SOA Record, NS Record, MX Record, etc. There are A records already added that link to your IP address, so you donβt have to worry about that. If you wanted to add a subdomain, you could create an A record here for that.
Like I said, it may take a few hours, but you should be all set. You have now deployed your application.
if you want to make changes to your app, just push to github and run a git pull on your server. There are other tools to help automate your deployments, but I will go over that another time.
Set Up SSL
You can purchase an SSL and set it with your domain registrar or you can use Letβs Encrypt and set one up for free using the following commands:
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install python-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
# Only valid for 90 days, test the renewal process with
certbot renew --dry-run
Comprehensive Guide: Docker, NGINX, and Production Node.js Deployment
This document provides a detailed, two-part guide: first, on setting up a basic NGINX web server using Docker for serving static files, and second, on deploying a production-ready Node.js application using NGINX as a reverse proxy with SSL security.
Part 1: Setting Up NGINX to Serve Static Files
This section focuses on containerization, basic package management, and NGINX configuration to serve a simple HTML and CSS website.
1. Docker Environment Setup
Docker is a platform used to develop, ship, and run applications in isolated environments called containers. Weβll use an Ubuntu container as our lightweight server environment.
Pulling and Running the Container
We use the docker run command to create and start the container, mapping a port on your host machine to the containerβs internal web server port.
| Command | Purpose |
|---|---|
docker pull ubuntu | Fetches the latest Ubuntu OS image from Docker Hub, the default public registry. |
docker run -it -p 9090:80 ubuntu | Runs a new container from the ubuntu image. |
-it | Allocates an interactive terminal (i) and keeps STDIN open (t), allowing you to interact with the containerβs shell. |
-p 9090:80 | Port mapping: Forwards traffic from the host machineβs port 9090 to the containerβs internal port 80 (where NGINX will listen). |
2. Installing Packages and Starting NGINX
Once inside the containerβs shell, we install the necessary tools.
Installation Commands
# Update package lists and upgrade installed packages
apt update && apt upgrade
# Install NGINX (the web server) and Neovim (a powerful text editor)
apt install nginx neovim
Verifying and Starting the Web Server
| Command | Purpose |
|---|---|
nginx -v | Verification: Confirms NGINX installed correctly and displays the version. |
nginx | Execution: Starts the NGINX web server process. By default, it listens for HTTP traffic on port 80 within the container. |
β οΈ Common Mistake: Missing the
-itflag If you omit the-itwhen running the container, the container will immediately exit because it has no foreground process to run. Solution: Usedocker run -it ...or usedocker start [container_id]anddocker attach [container_id]if itβs already created.
3. NGINX Configuration for Static Files
The primary NGINX configuration file is located at /etc/nginx/nginx.conf. We will modify this file to serve our websiteβs static content.
Configuration Workflow
- Navigate:
cd /etc/nginx - Backup:
mv nginx.conf nginx.backup(Preserves the default configuration) - Create/Edit:
nvim nginx.conf - Reload:
nginx -s reload(Applies the new configuration without stopping the server)
Creating the Static Content
We must create the website files before referencing them in the NGINX configuration.
# Create a root directory for the website inside /etc/nginx
mkdir MyWebSite
# Create the essential files
touch MyWebSite/index.html
touch MyWebSite/style.css
Sample Website Files
MyWebSite/index.html
<html>
<head>
<title>Ahmed X Nginx</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Hello From NGINX</h1>
<p>This is a simple NGINX WebPage</p>
</body>
</html>
MyWebSite/style.css
body {
background-color: black;
color: white;
}
Final NGINX Static File Configuration (nginx.conf)
This configuration tells NGINX where to find the files and how to handle file types.
events {
# The events block handles how NGINX manages connections (e.g., number of worker processes).
}
http {
# The http block contains server configurations.
# π MIME Types: Defines file extensions and their corresponding content types (crucial for browsers)
types {
text/css css;
text/html html;
}
server {
# The server block defines a virtual host.
listen 80; # Listen for HTTP requests on the container's port 80.
server_name _; # Wildcard: Matches requests for any domain name.
# π― Root Directive: Defines the base directory for file lookups.
root /etc/nginx/MyWebSite;
# When a request comes in (e.g., http://host:9090/), NGINX will look for
# index.html inside the directory defined by the 'root' directive.
}
}
Testing: After reloading NGINX (
nginx -s reload), you should be able to access the website by pointing your host machineβs browser tohttp://localhost:9090.
Part 2: Production Deployment of a Node.js Application
This section details using NGINX as a reverse proxy to deploy a Node.js application, including process management, firewall setup, and SSL encryption.
4. Application and Infrastructure Setup
In a production environment, we deploy the Node.js application on a high, non-standard port (e.g., 5173) and use NGINX to handle the public-facing traffic on the standard port (80/443).
Installing Required Tools
The installation command includes all necessary components for a robust deployment.
apt install git nvim nginx tmux nodejs ufw python3-certbot-nginx
| Tool | Purpose |
|---|---|
nodejs | The runtime environment for the application. |
git | For cloning the project source code. |
tmux | A terminal multiplexer for managing multiple sessions (useful for running background tasks). |
ufw | The Uncomplicated Firewall, used to secure the server. |
python3-certbot-nginx | The tool for obtaining and configuring SSL/TLS certificates from Letβs Encrypt. |
Cloning and Installing the Project
# Clone the repository containing the Node.js project
git clone https://github.com/akibahmed229/Java-Employee_Management-System-Website.git
# Navigate into the project folder
cd Java-Employee_Management-System-Website
# Install dependencies defined in package.json
npm install
Process Management and Firewall
We use PM2 (Process Manager 2) to ensure the Node.js application runs continuously and automatically restarts if it crashes.
-
Install PM2 globally:
sudo npm i pm2 -g -
Start the application:
pm2 start index.js --name "myapp" # Note: Using 'index.js' is more explicit than 'index' -
Enable Firewall:
# Enables the firewall (WARNING: This will block all unapproved traffic) ufw enable # Explicitly allow inbound HTTP traffic on standard web port 80 sudo ufw allow 'Nginx HTTP' # Or sudo ufw allow 80
5. Configuring NGINX as a Reverse Proxy
A reverse proxy sits in front of the application server, accepting client requests and forwarding them to the application. This setup centralizes security (SSL), load balancing, and static file serving, leaving the Node.js app to focus purely on business logic.
Reverse Proxy Configuration (/etc/nginx/nginx.conf)
events { }
http {
server {
# Listen for connections on standard HTTP port 80 (IPv4 and IPv6)
listen 80 default_server;
listen [::]:80 default_server;
server_name yourdomain.com www.yourdomain.com; # IMPORTANT: Replace with your actual domain
location / {
# π― The core reverse proxy directive: Forward requests to the Node.js app running locally on port 5173
proxy_pass http://localhost:5173;
# π€ Essential Proxy Headers for correct communication
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; # Required for WebSockets
proxy_set_header Connection 'upgrade'; # Required for WebSockets
proxy_set_header Host $host; # Passes the original domain name to the backend app
proxy_cache_bypass $http_upgrade; # Ensures WebSocket requests bypass any proxy cache
}
# NOTE: The original 'root /var/www/html;' and 'index ...' directives are typically
# removed or placed in a separate location block when using a reverse proxy for the root location.
}
}
QOL Enhancement: Using Multiple Config Files In production, itβs better practice to create a dedicated configuration file for your site in
/etc/nginx/sites-available/yourdomain.confand create a symbolic link to/etc/nginx/sites-enabled/. This avoids cluttering the mainnginx.confand makes managing multiple sites easier.
6. Securing with SSL/TLS (HTTPS)
SSL/TLS (Secure Sockets Layer/Transport Layer Security) encrypts communication between the userβs browser and the server, creating HTTPS. We use Certbot with the Letβs Encrypt service to automate this process.
Installing the Certificate
The certbot command automatically edits the NGINX configuration to redirect HTTP (port 80) traffic to HTTPS (port 443) and adds the necessary certificate files.
# This command automatically obtains a certificate for your domain and configures NGINX
certbot --nginx -d yourdomain.com -d www.yourdomain.com
Testing Automated Renewal
Letβs Encrypt certificates are only valid for 90 days, so automated renewal is essential.
# Performs a dry run to test the renewal process without actually renewing
certbot renew --dry-run
Best Practice: Port Management After enabling SSL, confirm your firewall (
ufw) is allowing HTTPS traffic on port 443:sudo ufw allow 'Nginx Full'.
Advanced Techniques: Optimizing a Dockerized NGINX/Node.js Stack
This section explores advanced concepts for performance, security, and maintainability in your deployed environment.
7. Performance and Hardening with NGINX
A. Caching Static Assets
NGINX can significantly improve page load times by caching static files like images, CSS, and JavaScript.
Advanced Configuration Snippet:
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
# Match common static file extensions
expires 30d; # Tell the client's browser to cache these files for 30 days
add_header Pragma "public";
add_header Cache-Control "public, must-revalidate, proxy-revalidate";
# Ensure NGINX serves these files directly (important when using a root directive)
root /path/to/static/assets;
# β οΈ Use a separate location block for caching, not the main proxy_pass block
}
B. Rate Limiting for Security
Rate limiting prevents abuse and Denial of Service (DoS) attacks by restricting the number of requests a single client can make over a period of time.
# 1. Define the limit zone in the http block
# 'mylimit' is the zone name, 1m is the size (1MB), and 5r/s is 5 requests per second
limit_req_zone $binary_remote_addr zone=mylimit:1m rate=5r/s;
server {
# 2. Apply the limit in the server or location block
location /login/ {
# Burst allows a short burst of requests above the limit before throttling.
limit_req zone=mylimit burst=10 nodelay;
proxy_pass http://localhost:5173;
}
}
8. Docker Best Practices and Automation
A. Using Multi-Stage Builds
When creating a production Docker image for a Node.js application, using a multi-stage build dramatically reduces the final image size by discarding build-time dependencies.
Conceptual Dockerfile Snippet:
# Stage 1: Build Stage (Uses a heavy image for building)
FROM node:20-slim as builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build # Assuming a build script exists
# Stage 2: Production Stage (Uses a tiny image for running)
FROM node:20-slim
WORKDIR /app
# Only copy the essential files from the builder stage
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/index.js ./ # Or whatever your entry file is
CMD [ "pm2-runtime", "start", "index.js" ]
B. PM2 Ecosystem File
Instead of managing startup via the command line, use a PM2 Ecosystem file (ecosystem.config.js) to standardize configuration, logging, and environment variables.
Example:
module.exports = {
apps: [
{
name: "node-app-prod",
script: "./index.js",
instances: "max", // Run on all available CPU cores
exec_mode: "cluster",
env: {
NODE_ENV: "production",
PORT: 5173,
},
},
],
};
Start command: pm2 start ecosystem.config.js
9. Troubleshooting and Diagnostics
A. Checking NGINX Configuration Errors
Before reloading NGINX, always check the configuration syntax to prevent downtime.
nginx -t
# Output should be: "syntax is ok" and "test is successful"
B. Diagnosing PM2/Node.js Issues
If your application isnβt responding through NGINX, check the logs and status of your PM2 process.
| Command | Purpose |
|---|---|
pm2 status | Shows the current running status, uptime, and process ID. |
pm2 logs myapp | Streams the applicationβs standard output and error logs in real-time. |
pm2 monit | Opens a real-time terminal dashboard to monitor CPU, Memory, and logs. |
Distubation
NixOS
NixOS Command Cheatsheet
A collection of useful Nix and NixOS commands for system management.
System & Store Maintenance
-
Verify & Repair Store: Checks the integrity of the Nix store and repairs any issues. Use this if you suspect corruption.
sudo nix-store --repair --verify --check-contents -
Garbage Collection: Removes all unused packages from the Nix store to free up space.
sudo nix-collect-garbage -d sudo nix-collect-garbage --delete-older-than 7d sudo nix store gc
Generation Management
-
List System Generations: Shows all past system configurations (generations).
sudo nix-env --list-generations --profile /nix/var/nix/profiles/system -
Switch Generation (No Reboot): Allows you to roll back to a previous system configuration without restarting.
-
List generations:
nix-env --list-generations -p /nix/var/nix/profiles/system -
Switch to generation:
sudo nix-env --switch-generation <number> -p /nix/var/nix/profiles/system -
Activate configuration:
sudo /nix/var/nix/profiles/system/bin/switch-to-configuration switch -
Set Booted Generation as Default: If you boot into an older generation, run this to make it the default.
/run/current-system/bin/switch-to-configuration boot
-
System Rebuilding
- Rebuild without Cache: Forces a rebuild without using cached tarballs.
sudo nixos-rebuild switch --flake .#host --option tarball-ttl 0 - Rebuild on a Remote Machine: Uses
sudoon a remote machine during activation.nixos-rebuild --use-remote-sudo switch --flake .#host
Flake Management
-
Update Flake Inputs: Updates flake dependencies and commits to
flake.lock.nix flake update --commit-lock-file --accept-flake-config -
Update Flake Inputs: Provide the git auth token to Updates flake dependencies and commits to
flake.lock. (fix api rate limit)nix flake update --option access-tokens "github.com=$(gh auth token)" -
Inspect Flake Metadata: Shows flake metadata in JSON format.
nix flake metadata --json | nix run nixpkgs#jq
Development & Packaging
-
Prefetch URL: Downloads a file and prints its hash. Essential for packaging.
nix-prefetch-url "https://discord.com/api/download?platform=linux&format=tar.gz" -
Evaluate a Nix File: Tests a Nix expression from a file.
nix-eval --file default.nix
Nixpkgs Legacy: Using Old OpenSSH with DSS
Sometimes you need to connect to legacy SSH servers that only support ssh-dss (DSA) keys. Modern Nixpkgs disables DSS by default, but you can pin an older package.
1. Create a Nix file for legacy OpenSSH
legacy-ssh.nix:
{ pkgs ? import <nixpkgs> {} }:
let
# Pin an older nixpkgs commit with DSS support
legacyPkgs = import (builtins.fetchTarball {
url = "https://github.com/NixOS/nixpkgs/archive/2f6ef9aa6a7eecea9ff7e185ca40855f36597327.tar.gz";
sha256 = "0jcs9r4q57xgnbrc76davqy10b1xph15qlkvyw1y0vk5xw5vmxfz";
}) {};
in
legacyPkgs.openssh
Browse older package versions: Nix Versions
2. Build the package
nix build -f legacy-ssh.nix
3. Use the legacy ssh binary
./result/bin/ssh -F /dev/null \
-o HostKeyAlgorithms=ssh-dss \
-o KexAlgorithms=diffie-hellman-group1-sha1 \
-o PreferredAuthentications=password,keyboard-interactive \
admin@192.168.0.1 -vvv
Explanation of key options:
-F /dev/nullβ Ignore default SSH config.HostKeyAlgorithms=ssh-dssβ Allow DSS host keys.KexAlgorithms=diffie-hellman-group1-sha1β Use legacy key exchange.PreferredAuthentications=password,keyboard-interactiveβ Only use password or interactive login.
NixOS with LUKS, LVM, and Btrfs: A Comprehensive Guide
π§ Table of Contents
- πΏ NixOS Installation: Manual Partitioning with LUKS + LVM + Btrfs
- β Extending an Encrypted LVM Volume with a New Disk
- β Removing an Encrypted Disk from an LVM Volume
- π LUKS Command Reference
- π LVM Command Reference
- π Btrfs Command Reference
- π§ System Recovery: Chrooting with a Live USB
1. πΏ NixOS Installation: Manual Partitioning with LUKS + LVM + Btrfs
This section guides you through a fresh installation of NixOS on a single disk.
Prerequisites
- Boot the NixOS installer.
- Connect to the internet.
- Switch to a
rootshell:sudo -i. - Identify your target disk:
lsblk. - Set a variable for your device:
export DEVICE=/dev/sda
Step 1. Wipe Disk and Create Partition Table
π¨ Warning: This will destroy all data on the specified disk.
vgchange -a n root_vg # deactivate the volume group
sgdisk --zap-all ${DEVICE}
# optional, override your disk with random data, take too long, hours.
dd if=/dev/urandom of=/dev/nvme01n bs=4096 status=progress
Step 2. Create Partitions
We will create a standard 4-partition layout for a modern UEFI system.
# Partition 1: 1M BIOS Boot partition (for GRUB compatibility)
sgdisk --new=1:0:+1M --typecode=1:EF02 --change-name=1:boot ${DEVICE}
# Partition 2: 500M EFI System Partition (ESP)
sgdisk --new=2:0:+500M --typecode=2:EF00 --change-name=2:ESP ${DEVICE}
# Partition 3: 4G Swap partition
sgdisk --new=3:0:+4G --typecode=3:8200 --change-name=3:swap ${DEVICE}
# Partition 4: The rest of the disk for our encrypted data
# We use 8E00 which is the typecode for "Linux LVM"
sgdisk --new=4:0:0 --typecode=4:8E00 --change-name=4:root ${DEVICE}
Step 3. Format Unencrypted Filesystems
Format the ESP and swap partitions, giving them labels for easy mounting.
# Format the EFI partition
mkfs.vfat -n ESP ${DEVICE}p2
# Set up the swap partition
mkswap -L swap ${DEVICE}p3
Step 4. Set Up LUKS Encryption and LVM π
This is the core of the setup. We create an encrypted container on our main partition and then build an LVM structure inside it.
# 1. Create the LUKS encrypted container on the fourth partition.
# You will be prompted to enter and confirm a strong passphrase. Remember this!
echo "Formatting the LUKS container. Please enter your encryption passphrase."
cryptsetup luksFormat -v -s 512 -h sha512 --label crypted ${DEVICE}p4
# 2. Open the LUKS container to make it accessible.
# This creates a decrypted "virtual" device at /dev/mapper/crypted.
echo "Opening the LUKS container. Please enter your passphrase."
cryptsetup open ${DEVICE}p4 crypted
# 3. Set up LVM *inside* the decrypted container.
# Initialize the physical volume (PV) on the decrypted device
pvcreate /dev/mapper/crypted
# Create the volume group (VG) named "root_vg"
vgcreate root_vg /dev/mapper/crypted
# Create the logical volume (LV) named "root" that uses all available space
lvcreate -l 100%FREE -n root root_vg
Step 5. Format the LVM Volume with Btrfs
Now, we format the LVM logical volume (not the physical partition) with Btrfs.
mkfs.btrfs -L root /dev/root_vg/root
Step 6. Create and Mount Btrfs Subvolumes
We use Btrfs subvolumes to separate parts of our system, which is standard practice for NixOS.
# 1. Mount the top-level Btrfs volume
mount /dev/root_vg/root /mnt
# 2. Create the subvolumes
btrfs subvolume create /mnt/root
btrfs subvolume create /mnt/persist
btrfs subvolume create /mnt/nix
# 3. Unmount the top-level volume
umount /mnt
# 4. Mount the root subvolume with correct options
mount -o subvol=root,compress=zstd,noatime /dev/root_vg/root /mnt
# 5. Create the directories for the other mountpoints
mkdir -p /mnt/persist
mkdir -p /mnt/nix
mkdir -p /mnt/boot
# 6. Mount the other subvolumes
mount -o subvol=persist,noatime,compress=zstd /dev/root_vg/root /mnt/persist
mount -o subvol=nix,noatime,compress=zstd /dev/root_vg/root /mnt/nix
Step 7. Mount Boot Partition and Activate Swap
Finish by mounting the ESP and activating the swap.
# Mount the boot partition
mount ${DEVICE}p2 /mnt/boot
# Activate the swap partition
swapon ${DEVICE}p3
Step 8. Generate NixOS Configuration
Finally, generate the NixOS configuration. The installer will automatically detect the LUKS and LVM setup.
nixos-generate-config --root /mnt
Your /mnt/etc/nixos/hardware-configuration.nix will be auto-generated with the correct LUKS and filesystem entries, similar to this:
# Example /etc/nixos/hardware-configuration.nix
{ config, lib, pkgs, modulesPath, ... }:
{
imports =
[ (modulesPath + "/profiles/qemu-guest.nix")
];
boot.initrd.availableKernelModules = [ "ahci" "xhci_pci" "virtio_pci" "sr_mod" "virtio_blk" ];
boot.initrd.kernelModules = [ "dm-snapshot" ];
boot.kernelModules = [ "kvm-intel" ];
boot.extraModulePackages = [ ];
# This part is automatically added to unlock your disk at boot
boot.initrd.luks = {
devices."crypted" = {
device = "/dev/disk/by-label/crypted";
preLVM = true;
};
};
# These are your Btrfs subvolumes
fileSystems."/" =
{ device = "/dev/mapper/root_vg-root";
fsType = "btrfs";
options = [ "subvol=root" ];
};
fileSystems."/persist" =
{ device = "/dev/mapper/root_vg-root";
fsType = "btrfs";
options = [ "subvol=persist" ];
};
fileSystems."/nix" =
{ device = "/dev/mapper/root_vg-root";
fsType = "btrfs";
options = [ "subvol=nix" ];
};
# Your boot and swap partitions
fileSystems."/boot" = {
device = "/dev/disk/by-label/ESP";
fsType = "vfat";
options = [ "fmask=0022" "dmask=0022" ];
};
swapDevices =[ { device = "/dev/disk/by-label/swap"; } ];
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
}
You can now proceed with editing your configuration.nix and running nixos-install.
2. β Extending an Encrypted LVM Volume with a New Disk
Use this guide when youβve added a new physical disk (e.g., /dev/vdb) and want to add its encrypted space to your existing root_vg.
π¨ Pre-flight Check: Backup
Before you begin, ensure you have a backup of any critical data.
Step 1. Partition and Label the New Disk
Weβll create a single partition on the new disk (/dev/vdb) and give it a partition label for easy identification.
# Open parted for /dev/vdb
sudo parted /dev/vdb
# Inside parted, run the following commands:
# (parted)
mklabel gpt
mkpart primary 0% 100%
name 1 crypted_ext
quit
This creates /dev/vdb1 and sets its partition name (label) to crypted_ext.
Step 2. Create and Open the LUKS Encrypted Container
Now, encrypt the new partition.
# Encrypt /dev/vdb1.
# -> IMPORTANT: Use the EXACT SAME password as your main encryption.
# -> This allows NixOS to unlock both with a single password prompt.
sudo cryptsetup luksFormat /dev/vdb1
# Open the new LUKS container so we can work with it.
sudo cryptsetup luksOpen /dev/vdb1 crypted_ext_mapper
The unlocked device is now available at /dev/mapper/crypted_ext_mapper.
Step 3. Integrate the New Encrypted Disk into LVM
Add the newly decrypted device as a Physical Volume (PV) to your existing Volume Group (VG).
# 1. Create a new Physical Volume (PV) on the unlocked container.
sudo pvcreate /dev/mapper/crypted_ext_mapper
# 2. Extend your existing 'root_vg' Volume Group with this new PV.
sudo vgextend root_vg /dev/mapper/crypted_ext_mapper
# 3. (Verification) Check your Volume Group. It should now be larger.
sudo vgs
Step 4. Extend the Logical Volume and Btrfs Filesystem
Make the new space available to your filesystem.
# 1. Extend the Logical Volume to use 100% of the new free space.
sudo lvextend -l +100%FREE /dev/mapper/root_vg-root
# 2. Resize the Btrfs filesystem to fill the newly expanded Logical Volume.
sudo btrfs filesystem resize max /
# 3. (Verification) Check your disk space.
df -h /
Step 5. Update configuration.nix
This is the most critical step. You must tell NixOS to unlock this second device at boot.
Edit your /etc/nixos/configuration.nix file and add the new device to boot.initrd.luks.
# Your configuration.nix
boot.initrd.luks = {
devices."crypted" = {
device = "/dev/disk/by-label/crypted"; # This is your original /dev/vda4
preLVM = true;
};
# --- ADD THIS NEW BLOCK ---
devices."crypted_ext" = {
# Use the partition label you set in Step 1
device = "/dev/disk/by-partlabel/crypted_ext";
preLVM = true;
allowDiscards = true; # Good practice for SSDs/VMs
};
};
Note on Passwords: Because you used the same password for both LUKS devices, NixOS will ask for your password only once at boot and use it to unlock both containers.
Step 6. Rebuild and Reboot
DO NOT REBOOT until you have applied the new configuration.
# Apply your new NixOS configuration
sudo nixos-rebuild switch
# Now it is safe to reboot
sudo reboot
3. β Removing an Encrypted Disk from an LVM Volume
This guide covers the complex process of removing a disk (e.g., /dev/vdb) from a Volume Group when your filesystem spans multiple disks.
π¨ WARNING: This is a high-risk operation. A mistake can lead to total data loss. Back up all critical data before proceeding. This process almost always requires booting from a Live Linux ISO because you cannot shrink a mounted root filesystem.
The Goal
Our goal is to move all data off /dev/vdb (which is part of root_vg) onto your other disk (/dev/mapper/crypted) and then remove /dev/vdb from the LVM setup.
The Problem
You cannot pvmove data off /dev/vdb because there is no free space on the other disk to move it to. You must first shrink your filesystem and logical volume to be smaller than the size of the disk you want to keep.
Example:
- Disk 1 (
/dev/mapper/crypted): 35G - Disk 2 (
/dev/vdb): 20G - Total
root_vgsize: 55G - Your Goal: You must shrink your Btrfs filesystem and LV to < 35G (e.g., 34G).
Step 1. Boot from a Live Linux ISO
- Attach a NixOS, Ubuntu, or other Linux ISO to your VM or machine and boot from it.
- Open a terminal.
Step 2. Unlock Encrypted Disks and Activate LVM
# 1. Unlock your *main* encrypted partition (the one you are keeping)
# Replace /dev/vda4 with your actual partition
sudo cryptsetup luksOpen /dev/vda4 crypted
# 2. Unlock the *second* disk's encrypted partition
# (This assumes /dev/vdb is encrypted, following the guide in section 2)
sudo cryptsetup luksOpen /dev/vdb1 crypted_ext
# 3. Activate the LVM Volume Group
sudo vgchange -ay
Step 3. Resize Btrfs and LV (Offline)
This is the most critical part.
# 1. Run a filesystem check (highly recommended)
sudo btrfs check /dev/mapper/root_vg-root
# 2. Shrink the Btrfs filesystem.
# We set it to 34G, which is smaller than our 35G target disk.
sudo btrfs filesystem resize 34G /dev/mapper/root_vg-root
# 3. Shrink the Logical Volume to match.
sudo lvreduce -L 34G /dev/mapper/root_vg-root
Step 4. Reboot into Your Normal System
The offline part is done.
sudo reboot
Remove the Live ISO and boot back into your NixOS. Your system will boot up on a smaller filesystem.
Step 5. Migrate Data and Remove the Disk (Online)
Now that you are back in your system, sudo vgs should show free space in root_vg.
# 1. Load the 'dm-mirror' module, which pvmove needs
sudo modprobe dm_mirror
# 2. Move all data extents off the disk you want to remove.
# This will move data from crypted_ext to the free space on crypted.
sudo pvmove -v /dev/mapper/crypted_ext_mapper
# 3. Remove the now-empty Physical Volume from the Volume Group.
sudo vgreduce root_vg /dev/mapper/crypted_ext_mapper
# 4. Remove the LVM metadata from the device.
sudo pvremove /dev/mapper/crypted_ext_mapper
Step 6. Update configuration.nix and Clean Up
- Edit your
/etc/nixos/configuration.nixand remove the entry forcrypted_extfromboot.initrd.luks. - Rebuild your system:
sudo nixos-rebuild switch - You can now safely close the LUKS container and reboot. The disk
/dev/vdbis completely free.sudo cryptsetup luksClose crypted_ext_mapper sudo reboot
4. π LUKS Command Reference
Common cryptsetup commands for managing LUKS devices.
-
Format a new LUKS container:
# --label is recommended for use in /dev/disk/by-label/ cryptsetup luksFormat --label crypted /dev/sda4 -
Open (decrypt) a container:
# This creates a device at /dev/mapper/my_decrypted_volume cryptsetup luksOpen /dev/sda4 my_decrypted_volume -
Close (lock) a container:
cryptsetup luksClose my_decrypted_volume -
Add a new password (key slot):
# You will be prompted for an *existing* password first. cryptsetup luksAddKey /dev/sda4 -
Remove a password:
# You will be prompted for the password you wish to remove. cryptsetup luksRemoveKey /dev/sda4 -
View header information (and key slots):
cryptsetup luksDump /dev/sda4 -
Resize an online LUKS container: (Useful if you resize the underlying partition).
cryptsetup resize my_decrypted_volume
5. π LVM Command Reference
Common commands for managing LVM.
Physical Volume (PV) - The Disks
-
Initialize a disk for LVM:
pvcreate /dev/mapper/crypted -
List physical volumes:
pvs pvdisplay -
Move data from one PV to another (within the same VG):
# Moves all data *off* /dev/sdb1 pvmove /dev/sdb1 # Moves data from /dev/sdb1 *to* /dev/sdc1 pvmove /dev/sdb1 /dev/sdc1 -
Remove LVM metadata from a disk:
# Only run this *after* removing the PV from its VG. pvremove /dev/sdb1
Volume Group (VG) - The Pool of Disks
- Create a new VG:
# Creates a VG named "my_vg" using two disks vgcreate my_vg /dev/sdb1 /dev/sdc1 - List volume groups:
vgs vgdisplay - Add a disk (PV) to an existing VG:
vgextend my_vg /dev/sdd1 - Remove a disk (PV) from a VG:
# The PV must be empty (use pvmove first). vgreduce my_vg /dev/sdb1 - Remove a VG:
# Make sure all LVs are removed first. vgremove my_vg
Logical Volume (LV) - The βPartitionsβ
-
Create a new LV:
# Create a 50G LV named "my_lv" from the "my_vg" pool lvcreate -L 50G -n my_lv my_vg # Create an LV using all remaining free space lvcreate -l 100%FREE -n my_other_lv my_vg -
List logical volumes:
lvs lvdisplay -
Extend an LV (and its filesystem):
# Extend the LV to be 100G in total lvresize -L 100G /dev/my_vg/my_lv # Add 20G to the LV's current size lvresize -L +20G /dev/my_vg/my_lv # Extend the LV to use all free space in the VG lvextend -l +100%FREE /dev/my_vg/my_lv # --- IMPORTANT --- # After extending, you must resize the filesystem inside it. # For ext4: resize2fs /dev/my_vg/my_lv # For btrfs: btrfs filesystem resize max /path/to/mountpoint -
Reduce an LV (and its filesystem): π¨ DANGEROUS! You must shrink the filesystem first.
# 1. Shrink the filesystem (e.g., ext4, UNMOUNTED) resize2fs /dev/my_vg/my_lv 40G # 2. Shrink the LV to match lvreduce -L 40G /dev/my_vg/my_lv # For Btrfs, you can often do it online: # 1. Shrink Btrfs btrfs filesystem resize 40G /path/to/mountpoint # 2. Shrink LV lvreduce -L 40G /dev/my_vg/my_lv -
Remove an LV:
# Make sure it's unmounted first. lvremove /dev/my_vg/my_lv
6. π Btrfs Command Reference
Common commands for managing Btrfs filesystems and subvolumes.
-
Format a device:
# -L sets the label mkfs.btrfs -L root /dev/my_vg/my_lv -
Resize a filesystem:
# Grow to fill the maximum available space (after an lvextend) btrfs filesystem resize max /path/to/mountpoint # Set to a specific size (e.g., 50G) btrfs filesystem resize 50G /path/to/mountpoint # Shrink by 10G btrfs filesystem resize -10G /path/to/mountpoint -
Show filesystem usage:
# Btrfs-aware 'df' btrfs filesystem df /path/to/mountpoint -
Create a subvolume:
# Mount the top-level (ID 5) volume first mount /dev/my_vg/my_lv /mnt # Create subvolumes btrfs subvolume create /mnt/root btrfs subvolume create /mnt/nix umount /mnt -
List subvolumes:
btrfs subvolume list /path/to/mountpoint -
Delete a subvolume:
# Deleting a subvolume is recursive and instant btrfs subvolume delete /mnt/nix -
Create a snapshot:
# Create a read-only snapshot of 'root' btrfs subvolume snapshot -r /mnt/root /mnt/root-snapshot # Create a writable snapshot (a clone) btrfs subvolume snapshot /mnt/root /mnt/root-clone -
Check a Btrfs filesystem (unmounted):
btrfs check /dev/my_vg/my_lv
7. π§ System Recovery: Chrooting with a Live USB
If your system fails to boot due to a broken configuration, a kernel panic, or a faulty GRUB, you can use a Live USB (like the NixOS installer) to chroot into your installation and fix it. The nixos-enter command is a powerful script that makes this much easier.
Prerequisites
- Boot from a NixOS installer ISO.
- Connect to the internet (if you need to download packages).
- Open a terminal and get a root shell:
sudo -i.
Step 1. Identify and Unlock LUKS Volumes
First, find your encrypted partitions.
lsblk
You will need to identify all partitions that are part of your LVM root_vg. In the setup from this guide, there are two: the main crypted partition (e.g., /dev/vda4) and the extended one crypted_ext (e.g., /dev/vdb1).
π¨ Important: You must unlock ALL LUKS volumes that are part of your Volume Group, otherwise LVM will fail to activate.
# Unlock the primary disk (e.g., /dev/vda4)
cryptsetup luksOpen /dev/vda4 crypted
# Unlock the extended disk (e.g., /dev/vdb1)
cryptsetup luksOpen /dev/vdb1 crypted_ext
Enter your single passphrase when prompted for each.
Step 2. Activate the LVM Volume Group
Tell LVM to scan for and activate the Volume Groups now available on the decrypted devices.
# Scan for and activate all volume groups
vgchange -ay
You should see a message that root_vg is now active.
Step 3. Mount Filesystems for nixos-enter
nixos-enter is smart, but it needs the root (/) and boot (/boot) partitions mounted at /mnt.
# 1. Mount the Btrfs root subvolume
# This is the subvolume you set for '/' in your configuration.nix
mount -o subvol=root /dev/mapper/root_vg-root /mnt
# 2. Mount the boot (ESP) partition
# This is VITAL for fixing GRUB. Find your ESP (e.g., /dev/vda2)
mkdir -p /mnt/boot
mount /dev/vda2 /mnt/boot
Step 4. Chroot into Your System
With the root and boot partitions mounted, you can now use nixos-enter. It will automatically find your /nix store and other subvolumes.
nixos-enter
Your prompt should change, and you are now βinsideβ your broken NixOS installation as the root user.
Step 5. Perform Repairs (Inside the Chroot)
Here are common fixes for a broken system.
Scenario 1: Fix a Broken configuration.nix
This is the most common fix. You made a change, rebuilt, and now it wonβt boot.
# 1. Edit your configuration to fix the typo or bad option
nano /etc/nixos/configuration.nix
# 2. Rebuild the system.
# 'nixos-rebuild switch' will build and make it the default.
nixos-rebuild switch
# If you are less confident, 'nixos-rebuild boot' will build it
# and set it as the default, but won't activate it immediately.
nixos-rebuild boot
Scenario 2: Roll Back to a Previous Generation
If you just want to undo your last build, you can roll back.
# This will build your *previous* configuration and make it the default.
nixos-rebuild boot --rollback
# You can also list all generations and switch to a specific one:
nix-env -p /nix/var/nix/profiles/system --list-generations
nix-env -p /nix/var/nix/profiles/system --switch-generation 123
Scenario 3: Manually Reinstall GRUB
If nixos-rebuild doesnβt fix a βno bootable deviceβ error, GRUB itself might be broken.
# This command reinstalls GRUB to your EFI directory.
grub-install --target=x86_64-efi --efi-directory=/boot --bootloader-id=nixos
After this, itβs still a good idea to run nixos-rebuild switch to ensure GRUBβs configuration file is also correct.
Step 6. Exit and Reboot
Once you are finished, exit the chroot and unmount everything.
# 1. Exit the chroot
exit
# 2. Unmount all partitions
umount -R /mnt
# 3. Reboot the system
reboot
Remove your Live USB, and your system should now boot into the fixed configuration.
Installation
Arch Linux Installation Guide
This guide provides step-by-step instructions for installing Arch Linux.
Table of Contents
- Keyboard Layout Setup
- Connecting to Wi-Fi
- SSH Connection to Another Device
- Date and Time Setup
- Disk Management for Installation
- System Installation
- Configuring the New Installation (arch-chroot)
- Edit The Mkinitcpio File For Encrypt
- Grub Installation
- Enabling Systemd Services
- Creating a New User
- Finishing the Installation
- Post-Installation Configuration
1. Keyboard Layout Setup
Load the keyboard layout using the following commands:
localectl
localectl list-keymaps
localectl list-keymaps | grep us
loadkeys us
Explanation:
localectl: Lists the current keyboard layout settings.localectl list-keymaps: Lists all available keyboard layouts.localectl list-keymaps | grep us: Filters the list to show only layouts containing βusβ (United States layout).loadkeys us: Sets the keyboard layout to US.
2. Connecting to Wi-Fi
Connect to a Wi-Fi network using the following commands:
iwctl
device list
station wlan0 get-networks
station wlan0 connect wifiname
ip a
ping -c 5 google.com
Explanation:
iwctl: Launches the interactive Wi-Fi control utility.device list: Lists available network devices.station wlan0 get-networks: Scans for available Wi-Fi networks.station wlan0 connect wifiname: Connects to the specified Wi-Fi network (replace βwifinameβ with the actual network name).ip a: Displays the network interfaces and their IP addresses.ping -c 5 google.com: Pings the Google website to test the internet connection.
3. SSH Connection to Another Device
Set a password and establish an SSH connection to another device:
passwd
ssh root@ipaddress
Explanation:
passwd: Sets the password for the current device (root user).ssh root@ipaddress: Connects to the current device using SSH from another device (replace βipaddressβ with the actual IP address of the current device).
4. Date and Time Setup
Set the date and time for the system:
timedatectl
timedatectl list-timezones
timedatectl list-timezones | grep Dhaka
timedatectl set-timezone Asia/Dhaka
timedatectl
Explanation:
timedatectl: Displays the current system time and date settings.timedatectl list-timezones: Lists all available time zones.timedatectl list-timezones | grep Dhaka: Filters the list to
show time zones containing βDhakaβ (replace with your desired time zone).
timedatectl set-timezone Asia/Dhaka: Sets the systemβs time zone to βAsia/Dhakaβ (replace with your desired time zone).timedatectl: Verifies the updated time and date settings.
5. Disk Management for Installation
Manage the disk partitions for the installation:
lsblk
ls /sys/firmware/efi/efivars
blkid /dev/vda
cfdisk
lsblk
mkfs.btrfs -f /dev/vda1
mkfs.fat -F32 /dev/vda2
blkid /dev/vda
mount /dev/vda1 /mnt
cd /mnt
btrfs subvolume create @
btrfs subvolume create @home
cd
umount /mnt
mount -o noatime,ssd,space_cache=v2,compress=zstd,discard=async,subvol=@ /dev/vda1 /mnt
mkdir /mnt/home
mount -o noatime,ssd,space_cache=v2,compress=zstd,discard=async,subvol=@home /dev/vda1 /mnt/home
mkdir -p /mnt/boot/efi
mount /dev/vda2 /mnt/boot/efi
mkdir /mnt/windows
lsblk
Explanation:
lsblk: Lists available block devices and their partitions.ls /sys/firmware/efi/efivars: Verifies if the system is booted in UEFI mode.blkid /dev/sda: Displays information about the /dev/sda drive (replace with the appropriate drive if different).cfdisk: # create two pertion 1. Main file 2. efi partion
disk encryption
-
cryptsetup luksformat /dev/vda1: setup encryption -
cryptsetup luksOpen /dev/vda1 main: open your encrypted partition -
lsblk: Lists the updated block devices and their partitions after partitioning. -
mkfs.btrfs -f /dev/mapper/main: Formats the System partition (/dev/vda1 or (main)) as Btrfs. -
mkfs.fat -F32 -f /dev/vda2: Formats the EFI System partition (/dev/vda2) as FAT32. -
blkid /dev/vda: Verifies the UUID of the formatted partition. -
mount /dev/mapper/main /mnt: Mounts the System partition (main) to the /mnt directory. -
cd /mnt: Changes the current directory to /mnt. -
fat subvolume create @: Creates a Btrfs subvolume named β@β for the root directory. -
fat subvolume create @home: Creates a Btrfs subvolume named β@homeβ for the home directory. -
cd: Returns to the previous directory. -
umount /mnt: Unmounts the /mnt directory. -
mount -o noatime,ssd,space_cache=v2,compress=zstd,discard=async,subvol=@ /dev/vda1 /mnt: Mounts the System partition (/dev/vda1) with Btrfs subvolume β@β, applying specified mount options. -
mkdir /mnt/home: Creates the /mnt/home directory. -
mount -o noatime,ssd,space_cache=v2,compress=zstd,discard=async,subvol=@home /dev/vda1 /mnt/home: Mounts the System partition (/dev/vda1) with Btrfs subvolume β@homeβ to the /mnt/home directory, applying specified mount options. -
mkdir -p /mnt/boot/efi: Creates the /mnt/boot/efi directory. -
mount /dev/vda1 /mnt/boot/efi: Mounts the EFI System partition (/dev/vda2) to the /mnt/boot/efi directory.
(Optional) For Windows partition:
mkdir /mnt/windows: Creates the /mnt/windows directory.lsblk: Lists available block devices and their partitions to identify the Windows partition.
6. System Installation
Install the base system:
reflector --country Bangladesh --age 6 --sort rate --save /etc/pacman.d/mirrorlist
pacman -Sy
pacstrap -K /mnt base linux linux-firmware intel-ucode vim
genfstab -U /mnt >> /mnt/etc/fstab
cat /mnt/etc/fstab
Explanation:
reflector --country Bangladesh --age 6 --sort rate --save /etc/pacman.d/mirrorlist: Updates the mirrorlist file with the fastest mirrors in Bangladesh (replace with your desired country).pacman -Sy: Synchronizes package databases.pacstrap -K /mnt base linux linux-firmware intel-ucode vim: Installs essential packages (replace with any additional packages you may need).genfstab -U /mnt >> /mnt/etc/fstab: Generates an fstab file based on the current disk configuration.cat /mnt/etc/fstab: Displays the contents of the generated fstab file for verification.
7. Configuring the New Installation (arch-chroot)
Enter the newly installed system for configuration:
arch-chroot /mnt
ls
ln -sf /usr/share/zoneinfo/Asia/Dhaka /etc/localtime
hwclock --systohc
vim /etc/locale.gen
locale-gen
echo "LANG=en_US.UTF-8" >> /etc/locale.conf
echo "KEYMAP=us" >> /etc/vconsole.conf
vim /etc/hostname
passwd
pacman -S grub-btrfs efibootmgr networkmanager network-manager-applet dialog wpa_supplicant mtools dosfstools reflector base-devel linux-headers bluez bluez-utils cups hplip alsa-utils pipewire pipewire-alsa pipewire-pulse pipewire-jack bash-completion openssh rsync acpi acpi_call tlp sof-firmware acpid os-prober ntfs-3g
Explanation:
arch-chroot /mnt: Changes the root to the newly installed system (/mnt).ls: Lists the contents of the root directory to verify the chroot environment.ln -sf /usr/share/zoneinfo/Asia/Dhaka /etc/localtime: Creates a symbolic link from the systemβs time zone file to /etc/localtime, setting the systemβs time zone to βAsia/Dhakaβ (replace with your desired time zone).hwclock --systohc: Sets the hardware clock from the system clock.vim /etc/locale.gen: Opens the locale.gen file for editing.- Uncomment the line containing βen_US.UTF-8β by removing the leading β#β character.
locale-gen: Generates the locales based on the uncommented entries in locale.gen.echo "LANG=en_US.UTF-8" >> /etc/locale.conf: Sets the LANG variable in locale.conf to βen_US.UTF-8β.echo "KEYMAP=us" >> /etc/vconsole.conf: Sets the KEYMAP variable in vconsole.conf to βusβ (replace with your desired keyboard layout).vim /etc/hostname: Opens the hostname file for editing.- Set the hostname to βarchβ (replace with your desired hostname).
passwd: Sets the root password.pacman -S grub efibootmgr networkmanager network-manager-applet dialog wpa_supplicant mtools dosfstools reflector base-devel linux-headers bluez bluez-utils cups hplip alsa-utils pipewire pipewire-alsa pipewire-pulse pipewire-jack bash-completion openssh rsync acpi acpi_call tlp sof-firmware acpid os-prober ntfs-3g: Installs various packages necessary for the system, including GRUB, network management tools, Bluetooth support, printer support, audio utilities, and other useful packages. Adjust the list based on your requirements.
8. Edit The Mkinitcpio File For Encrypt
vim /etc/mkinitcpio.confand search for HOOKS;- add encrypt (before filesystems hook);
- add
atkbdto the MODULES (enables external keyboard at device decryption prompt); - add
btrfsto the MODULES; and, - recreate the
mkinitcpio -p linux
9. Grub Installation
Install and configure Grub:
grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=GRUB
grub-mkconfig -o /boot/grub/grub.cfg
vim /etc/default/grub
grub-mkconfig -o /boot/grub/grub.cfg
- run blkid and obtain the UUID for the main partitin:
blkid /dev/vda1 - edit the grub config
nvim /etc/default/grub GRUB_CMDLINE_LINUX_DEFAULT="loglevel=3 quiet cryptdevice=UUID=d33844ad-af1b-45c7-9a5c-cf21138744b4:main root=/dev/mapper/main- make the grub config with
grub-mkconfig -o /boot/grub/grub.cfg
Explanation:
grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=GRUB: Installs GRUB bootloader on the EFI System partition (/dev/vda2) with the bootloader ID βGRUBβ.grub-mkconfig -o /boot/grub/grub.cfg: Generates the GRUB configuration file based on the installed operating systems.vim /etc/default/grub: Opens the GRUB configuration file for editing.- Uncomment the line with βos-proberβ by removing the leading β#β character. This allows GRUB to detect other installed operating systems.
grub-mkconfig -o /boot/grub/grub.cfg: Generates the GRUB configuration file again to include the changes made.
10. Enabling Systemd Services
Enable necessary systemd services:
systemctl enable NetworkManager
systemctl enable bluetooth
systemctl enable cups.service
systemctl enable sshd
systemctl enable tlp
systemctl enable reflector.timer
systemctl enable fstrim.timer
systemctl enable acpid
Explanation:
systemctl enable NetworkManager: Enables the NetworkManager service to manage network connections.systemctl enable bluetooth: Enables the Bluetooth service.systemctl enable cups.service: Enables the CUPS (Common Unix Printing System) service for printer support.systemctl enable sshd: Enables the SSH server for remote access.systemctl enable tlp: Enables the TLP service for power management.systemctl enable reflector.timer: Enables the Reflector timer to update the mirrorlist regularly.systemctl enable fstrim.timer: Enables the fstrim timer to trim the filesystem regularly.systemctl enable acpid: Enables the ACPI (Advanced Configuration and Power Interface) service.
11. Creating a New User
Create a new user and grant sudo access:
useradd -m akib
passwd akib
echo "akib ALL=(ALL) ALL" >> /etc/sudoers.d/akib
usermod -c 'Akib Ahmed' akib
exit
Explanation:
useradd -m akib: Creates a new user account named βakibβ with the-mflag to create the userβs home directory.passwd akib: Sets the password for the newly created user βakibβ.echo "akib ALL=(ALL) ALL" >> /etc/sudoers.d/akib: Grants sudo access to the user βakibβ by adding a sudoers file for the user.usermod -c 'Akib Ahmed' akib: Sets the userβs full name as βAkib Ahmedβ (replace with the desired full name).exit: Exits the chroot environment.
12. Finishing the Installation
Unmount partitions and reboot the system:
umount -R /mnt
reboot
Explanation:
umount -R /mnt: Unmounts all the partitions mounted under /mnt.reboot: Reboots the system.
Once the system reboots, you can log in with the newly created user and continue the setup process.
13. Post-Installation Configuration
After logging in with the newly created user, perform the following steps:
nmtui
- Opens the NetworkManager Text User Interface (TUI) for managing network connections.
ip -c a
- Displays the IP addresses and network interfaces for verification.
grub-mkconfig -o /boot/grub/grub.cfg
- Generates the GRUB configuration file to include any changes made during the post-installation steps.
sudo pacman -S git
- Installs the Git package.
git clone https://aur.archlinux.org/yay-bin.git
- Clones the Yay AUR (Arch User Repository) package from the AUR repository.
ls
cd yay-bin/
makepkg -si
cd
- Changes directory to the cloned βyay-binβ directory, builds the package, and installs it using
makepkg.
yay
- Verifies the successful installation of Yay by running the command.
yay -S timeshift-bin timeshift-autosnap
- Installs the Timeshift packages from the AUR using Yay.
sudo timeshift --list-devices
- Lists the available devices for creating Timeshift snapshots.
sudo timeshift --snapshot-device /dev/vda1
- Sets the device (/dev/vda1) to be used for creating Timeshift snapshots.
sudo timeshift --create --comments "First Backup" --tags D
- Creates a Timeshift snapshot with a comment and assigns it the βDβ tag for easy identification.
sudo grub-mkconfig -o /boot/grub/grub.cfg
- Generates the GRUB configuration file again to include any changes made during the post-installation steps.
Ensure you have read and understood each step before proceeding. These additional steps cover various post-installation configurations, including network setup, package installation with Yay, and creating a Timeshift backup.
Happy Arch Linux configuration! π§
Gentoo Installation Guide
This comprehensive guide provides a detailed walkthrough for installing Gentoo Linux. Adjustments may be required based on your specific hardware and preferences.
Prerequisites
- A reliable internet connection.
- A virtual or physical machine with a target disk (e.g., /dev/vdx).
1. Check Internet Connection
Make sure your internet connection is working:
ping -c 5 www.google.com
2. Disk Partitioning
Partition your disk using fdisk:
fdisk /dev/vdx
Follow these steps in fdisk:
- Press
gfor GPT partition. - Create partitions for boot, swap, and root using
n. - Change partition labels using
t: set boot to EFI, swap to Linux swap.
Format partitions:
mkfs.vfat -F 32 /dev/vdx1
mkswap /dev/vdx2
swapon /dev/vdx2
mkfs.ext4 /dev/vdx4
Mount the root partition:
mkdir -p /mnt/gentoo
mount /dev/sda3 /mnt/gentoo
3. Installing a Stage Tarball
Navigate to the Gentoo mirrors and download the stage3 tarball:
cd /mnt/gentoo
links https://www.gentoo.org/downloads/mirrors/
tar xpvf stage3-*.tar.xz --xattrs-include='*.*' --numeric-owner
vi /mnt/gentoo/etc/portage/make.conf
In make.conf, specify your CPU architecture and core:
COMMON_FLAGS="-march=alderlake -O2 -pipe"
MAKEOPTS="-j8"
FEATURES="candy parallel-fetch parallel-install"
ACCEPT_LICENSE="*"
4. Installing the Gentoo Base System
Select a mirror:
mirrorselect -i -o >> /mnt/gentoo/etc/portage/make.conf
Create necessary directories:
mkdir -p /mnt/gentoo/etc/portage/repos.conf
cp /mnt/gentoo/usr/share/portage/config/repos.conf /mnt/gentoo/etc/portage/repos.conf/gentoo.conf
cp --dereference /etc/resolv.conf /mnt/gentoo/etc/
Mount essential filesystems:
mount --types proc /proc /mnt/gentoo/proc
mount --rbind /sys /mnt/gentoo/sys
mount --make-rslave /mnt/gentoo/sys
mount --rbind /dev /mnt/gentoo/dev
mount --make-rslave /mnt/gentoo/dev
mount --bind /run /mnt/gentoo/run
mount --make-slave /mnt/gentoo/run
Chroot into the new environment:
chroot /mnt/gentoo /bin/bash
source /etc/profile
export PS1="(chroot) ${PS1}"
Mount the EFI boot partition:
mkdir /efi
mount /dev/sda1 /efi
5. Configuring Portage Package Manager of Gentoo
emerge-webrsync
emerge --sync
emerge --sync --quiet
eselect profile list
eselect profile set 9
emerge --ask --verbose --update --deep --newuse @world
nano /etc/portage/make.conf
In make.conf, add USE flags:
USE="-gtk -gnome qt5 kde dvd alsa cdr"
Create a package.license directory and edit the kernel license:
mkdir /etc/portage/package.license
nvim /etc/portage/package.license/kernel
Add the following licenses:
app-arch/unrar unRAR
sys-kernel/linux-firmware @BINARY-REDISTRIBUTABLE
sys-firmware/intel-microcode intel-ucode
6. Timezone and Locale Configuration
Set your timezone:
ls /usr/share/zoneinfo
echo "Asia/Dhaka" > /etc/timezone
emerge --config sys-libs/timezone-data
Configure locales:
emerge app-editors/neovim
nvim /etc/locale.gen
Uncomment the necessary locales and set the default:
en_US ISO-8859-1
en_US.UTF-8 UTF-8
Set the locale:
locale-gen
eselect locale list
eselect locale set 6
env-update && source /etc/profile && export PS1="(chroot) ${PS1}"
7. Configuring the Kernel
emerge --ask sys-kernel/linux-firmware
emerge --ask sys-kernel/gentoo-sources
eselect kernel list
eselect kernel set 1
emerge --ask sys-apps/pciutils
cd /usr/src/linux
make menuconfig
make && make modules_install
make install
Alternatively, use Genkernel:
emerge --ask sys-kernel/linux-firmware
emerge --ask sys-kernel/genkernel
genkernel --mountboot --install all
ls /boot/vmlinu* /boot/initramfs*
ls /lib/modules
Or, Use the binary kernel:
emerge --ask sys-kernel/gentoo-kernel
emerge --ask --autunmust-write sys-kernel/gentoo-kernel-bin
etc-update
emerge -a sys-kernel/gentoo-kernel-bin
8. Configuring Fstab and Networking
Edit fstab to reflect your disk configuration:
neovim /etc/fstab
Add entries for EFI, swap, and root partitions:
/dev/vdx1 /efi vfat defaults 0 2
/dev/vdx2 none swap sw 0 0
/dev/vdx3 / ext4 defaults,noatime 0 1
Configure networking:
echo virt > /etc/hostname
emerge --ask --noreplace net-misc/netifrc
nvim /etc/conf.d/net
Add your network configuration:
config_enp1s0="dhcp"
Set networking to start at boot:
cd /etc/init.d
ln -s net.lo net.enp1s0
rc-update add net.enp1s0 default
9. Editing Hosts and System Configuration
Edit the hosts file:
nano /etc/hosts
Add or edit the hosts file with appropriate entries:
127.0.0.1 virt localhost
::1 virt localhost
Set system information:
passwd
nano /etc/conf.d/hwclock
Edit hwclock configuration:
clock="local"
10. System Logger and Additional Software
emerge --ask app-admin/sysklogd
rc-update add sysklogd default
rc-update add sshd default
nano -w /etc/inittab
Add SERIAL CONSOLES configuration:
s0:12345:respawn:/sbin/agetty 9600 ttyS0 vt100
s1:12345:respawn:/sbin/agetty 9600 ttyS1 vt100
Install additional software:
emerge --ask sys-fs/e2fsprogs
emerge --ask sys-block/io-scheduler-udev-rules
emerge --ask net-misc/dhcpcd
emerge --ask net-dialup/ppp
emerge --ask net-wireless/iw net-wireless/wpa_supplicant
11. Boot Loader
echo 'GRUB_PLATFORMS="efi-64"' >> /etc/portage/make.conf
emerge --ask --verbose sys-boot/grub
grub-install --target=x86_64-efi --efi-directory=/efi
grub-mkconfig -o /boot/grub/grub.cfg
exit
cd
umount -l /mnt/gentoo/dev{/shm,/pts,}
umount -R /mnt/gentoo
reboot
12. Adding a User for Daily Use
useradd -m -G users,wheel,audio -s /bin/bash akib
passwd akib
Removing Tarballs
rm /stage3-*.tar.*
13. Sound (PipeWire) Setup
emerge -av media-libs/libpulse
emerge --ask media-video/pipewire
emerge --ask media-video/wireplumber
usermod -aG pipewire akib
emerge --ask sys-auth/rtkit
usermod -rG audio akib
mkdir /etc/pipewire
cp /usr/share/pipewire/pipewire.conf /etc/pipewire/pipewire.conf
mkdir ~/.config/pipewire
cp /usr/share/pipewire/pipewire.conf ~/.config/pipewire/pipewire.conf
Add the following configuration to ~/.config/pipewire/pipewire.conf:
context.properties = {
default.clock.rate = 192000
default.clock.allowed-rates = [ 192000 48000 44100 ] # Up to 16 can be specified
}
14. Xorg Setup
Edit /etc/portage/make.conf and add the following:
USE="X"
INPUT_DEVICES="libinput synaptics"
VIDEO_CARDS="nouveau"
VIDEO_CARDS="radeon"
Install Xorg drivers and server:
emerge --ask --verbose x11-base/xorg-drivers
emerge --ask x11-base/xorg-server
env-update
source /etc/profile
15. Setting up Display Manager (SDDM)
emerge --ask x11-misc/sddm
usermod -a -G video sddm
vim /etc/sddm.conf
Add the following lines:
[X11]
DisplayCommand=/etc/sddm/scripts/Xsetup
Create /etc/sddm/scripts/Xsetup:
mkdir -p /etc/sddm/scripts
chmod a+x /etc/sddm/scripts/Xsetup
Edit /etc/conf.d/xdm and add:
DISPLAYMANAGER="sddm"
Enable the display manager at boot:
rc-update add xdm default
emerge --ask gui-libs/display-manager-init
vim /etc/conf.d/display-manager
From there add,
CHECKVT=7
DISPLAYMANAGER="sddm"
after that add it to the service,
rc-update add display-manager default
rc-service display-manager start
16. Desktop Installation (KDE Plasma)
eselect profile list
eselect profile set X
Set the number according to the desktop environment you want. For KDE Plasma:
emerge --ask kde-plasma/plasma-meta
emerge konsole
emerge firefox-bin
Create ~/.xinitrc and add:
#!/bin/sh
exec dbus-launch --exit-with-session startplasma-x11
Feel free to customize this guide further based on your specific needs and preferences.
This guide is designed to provide a comprehensive and detailed walkthrough for installing Gentoo Linux. Feel free to customize it further based on your specific needs and preferences.
Tools
The Complete Linux & Bash Command-Line Guide
Master the Linux command line from first principles to advanced automation. This comprehensive guide organizes commands by what you want to accomplish, making it your go-to reference whether youβre taking your first steps or optimizing complex workflows.
π§ Table of Contents
- Foundations: Understanding the Command Line
- Navigation: Finding Your Way Around
- File Operations: Creating, Moving, and Deleting
- Reading and Viewing Files
- Searching: Finding Files and Text
- Advanced Text Processing: Power Tools
- Users, Permissions, and Access Control
- Process and System Management
- Networking Essentials
- Archives and Compression
- Bash Scripting: Automating Tasks
- Input/Output Redirection
- Advanced Techniques and Power User Features
- Troubleshooting and Debugging
1. Foundations: Understanding the Command Line
The Anatomy of a Command
Every Linux command follows a predictable pattern that, once understood, unlocks the entire system:
command -options arguments
command: The program or tool youβre invoking (likelsto list files)-options: Modifiers that change behavior, also called flags or switches (like-lfor βlong formatβ)arguments: What you want the command to operate on (like/home/user)
Example breakdown:
ls -la /var/log
β β ββ argument (which directory)
β βββββ options (long format + all files)
ββββββββ command (list contents)
The Pipe: Your Most Powerful Tool
The pipe operator | is the cornerstone of command-line productivity. It channels the output of one command directly into the input of another, letting you chain simple tools into sophisticated operations.
cat server.log | grep "ERROR" | wc -l
What happens here:
catoutputs the entire log file|feeds that output togrepgrepfilters for lines containing βERRORβ|feeds those filtered lines towcwc -lcounts how many lines remain
Think of pipes as assembly lines: each command does one thing well, then passes its work to the next station.
Essential Survival Skills
Getting Help When Youβre Stuck
man command_name
The man (manual) command is your built-in encyclopedia. Every standard command has a manual page explaining its purpose, options, and usage. Navigate with arrow keys, search with /search_term, and quit with q.
β οΈ Common Mistake: Forgetting that man exists and searching online first. While web searches are valuable, man pages are authoritative, always available offline, and specific to your systemβs version.
Quick reference alternatives:
command --helporcommand -h: Brief usage summary (faster thanman)apropos keyword: Search all manual pages for a keyword
Tab Completion: Stop Typing So Much
Press Tab at any point while typing a command, filename, or path. The shell will:
- Complete the word if thereβs only one match
- Show you all possibilities if there are multiple matches
- Save you from typos and help you discover available options
Pro tip: Double-tap Tab twice quickly to see all possible completions without typing anything.
Quoting Rules That Matter
Quotes arenβt stylisticβthey fundamentally change how the shell interprets your input:
Double quotes ": The shell expands variables and substitutions
echo "Hello, $USER" # Outputs: Hello, akib
echo "Current dir: $(pwd)" # Outputs: Current dir: /home/akib
Single quotes ': Everything is literalβno expansions occur
echo 'Hello, $USER' # Outputs: Hello, $USER
echo 'Cost: $50' # Outputs: Cost: $50
When to use which:
- Use double quotes by default for strings containing variables
- Use single quotes when you want literal text (like in
sedorawkpatterns) - Use no quotes for simple, single-word arguments
The sudo Privilege System
Linux protects critical system operations by requiring administrator privileges. Rather than logging in as the dangerous βrootβ user, use sudo to execute individual commands with elevated rights:
sudo apt update # Update package lists (requires admin)
sudo reboot # Restart the system
How it works: sudo (Superuser Do) temporarily grants your command root privileges. Youβll be prompted for your password the first time, then you have a grace period (typically 15 minutes) before it asks again.
β οΈ Warning: With great power comes great responsibility. sudo can break your system if misused. Always double-check commands that start with sudo.
2. Navigation: Finding Your Way Around
Understanding Where You Are
The Linux filesystem is a tree structure. Unlike Windows with its separate drives (C:, D:), everything branches from a single root /.
pwd
Print Working Directory shows your current location:
/home/akib/projects/website
Best practice: Run pwd when youβre disoriented. Itβs free and instant.
Seeing Whatβs Around You
ls
The list command shows directory contents, but itβs far more powerful with options:
ls -la
This is the command youβll use 90% of the time:
-l: Long format showing permissions, owner, size, date-a: Show all files, including hidden ones (starting with.)
Output anatomy:
drwxr-xr-x 5 akib akib 4096 Oct 24 10:30 Documents
-rw-r--r-- 1 akib akib 2048 Oct 23 15:42 notes.txt
βββββββββ β β β β β ββ filename
βββββββββ β β β β ββββββββββββ modification date
βββββββββ β β β βββββββββββββββββ size in bytes
βββββββββ β β βββββββββββββββββββββββ group
βββββββββ β ββββββββββββββββββββββββββββ owner
βββββββββ ββββββββββββββββββββββββββββββ number of links
ββββββββββββββββββββββββββββββββββββββββββ permissions (others)
ββββββββββββββββββββββββββββββββββββββββββ permissions (group)
ββββββββββββββββββββββββββββββββββββββββββ permissions (owner)
ββββββββββββββββββββββββββββββββββββββββββ execute/search
ββββββββββββββββββββββββββββββββββββββββββ write
ββββββββββββββββββββββββββββββββββββββββββ read
ββββββββββββββββββββββββββββββββββββββββββ file type (d=directory, -=file)
Useful variations:
ls -lh: Human-readable sizes (2.1M instead of 2048576)ls -lt: Sort by time (newest first)ls -lS: Sort by Size (largest first)ls -lR: Recursive (show subdirectories too)
Moving Between Directories
cd directory_name
Change Directory is your navigation command. It understands both absolute and relative paths:
Absolute paths start from root /:
cd /var/log # Go directly to /var/log from anywhere
Relative paths start from your current location:
cd Documents # Go into Documents subdirectory
cd ../Downloads # Go up one level, then into Downloads
cd ../../shared/data # Go up two levels, then down a different branch
Special shortcuts:
cd # Go to your home directory (/home/username)
cd ~ # Same as above (~ means "home")
cd - # Return to previous directory (like "back" button)
cd .. # Go up one directory level
cd ../.. # Go up two levels
β οΈ Common Mistake: Forgetting that cd without arguments takes you home. If you accidentally run cd and lose your place, use cd - to get back.
Advanced Navigation: The Directory Stack
For power users who jump between multiple locations:
pushd /var/log # Save current location, jump to /var/log
pushd ~/projects # Save /var/log, jump to ~/projects
dirs # View the stack
popd # Return to /var/log
popd # Return to original location
Why use this? When youβre working across multiple directory trees (e.g., comparing logs in /var/log with configs in /etc while editing code in ~/projects), the directory stack is faster than repeatedly typing full paths.
Clearing the Clutter
clear
Clears your terminal screen without affecting your work. Useful when output has become overwhelming.
Keyboard shortcut: Ctrl+L does the same thing (faster than typing).
3. File Operations: Creating, Moving, and Deleting
Creating Files
touch filename.txt
Creates an empty file or updates the timestamp on an existing file. While touch seems simple, itβs essential for:
- Creating placeholder files
- Resetting modification times
- Testing write permissions in a directory
Why the name βtouchβ? It βtouchesβ the file, updating its access time without modifying contents.
Creating Directories
mkdir new_folder
Make Directory creates a new folder. But the real power comes with options:
mkdir -p path/to/deeply/nested/folder
The -p (parents) flag creates all intermediate directories automatically. Without it, youβd need to create each level separately:
# Without -p (tedious):
mkdir path
mkdir path/to
mkdir path/to/deeply
mkdir path/to/deeply/nested
mkdir path/to/deeply/nested/folder
# With -p (elegant):
mkdir -p path/to/deeply/nested/folder
Best practice: Always use -p unless you specifically want an error when parent directories donβt exist.
Copying Files and Directories
cp source.txt destination.txt
Copy creates a duplicate of a file:
# Copy and rename:
cp report.txt report_backup.txt
# Copy to another directory (keeping same name):
cp report.txt ~/Documents/
# Copy to another directory with new name:
cp report.txt ~/Documents/final_report.txt
For directories, use -r (recursive):
cp -r project/ project_backup/
Without -r, youβll get an error: cp: -r not specified; omitting directory 'project/'
Useful options:
-i: Interactiveβprompt before overwriting-v: Verboseβshow whatβs being copied-u: Updateβonly copy if source is newer than destination-a: Archive modeβpreserves permissions, timestamps, and structure (ideal for backups)
Pro tip: Combine flags for safety and visibility:
cp -riv source/ destination/
Moving and Renaming
mv old_name.txt new_name.txt
Move serves double duty:
Renaming (destination in same directory):
mv draft.txt final.txt
Moving (destination in different directory):
mv final.txt ~/Documents/
Moving and renaming simultaneously:
mv draft.txt ~/Documents/final.txt
Moving directories (no -r flag needed):
mv old_folder/ new_location/
β οΈ Warning: Unlike cp, mv doesnβt have a built-in way to prevent overwriting. Use -i for safety:
mv -i source.txt destination.txt # Prompts if destination exists
Deleting Files
rm filename.txt
Remove permanently deletes files. There is no βRecycle Binβ or βTrashβ on the command lineβonce removed, files are gone.
β οΈ CRITICAL WARNING: The most dangerous command in Linux is:
sudo rm -rf /
NEVER RUN THIS. It recursively (-r) and forcefully (-f) deletes everything on your system, including the operating system itself.
Safe deletion practices:
# Delete a single file:
rm old_file.txt
# Delete with confirmation:
rm -i file.txt # Prompts before deleting
# Delete multiple files:
rm file1.txt file2.txt file3.txt
# Delete directories (requires -r):
rm -r old_folder/
# Force deletion without prompts (use cautiously):
rm -rf temporary_folder/
Protecting yourself:
- Always double-check the path before using
-r - Use
lsfirst to verify what youβre about to delete - Never use
-rftogether unless youβre certain - Consider aliasing
rmtorm -iin your.bashrcfor an automatic safety net
Alternative for empty directories:
rmdir empty_folder/
This only works on empty directories, providing a safety check against accidental deletion.
Creating Links
ln -s /path/to/original /path/to/link
Links are like shortcuts or references. The -s creates a symbolic (soft) linkβthe most commonly used type.
Symbolic links point to a file path:
ln -s /var/www/html/index.php ~/index_link.php
Now you can edit ~/index_link.php and the changes affect the original file in /var/www/html/.
Real-world use cases:
- Creating shortcuts to deeply nested files
- Maintaining multiple versions (link to the current version)
- Organizing files without duplicating them
- Cross-referencing configurations
Viewing links:
ls -l
# Output: lrwxrwxrwx ... index_link.php -> /var/www/html/index.php
# ^
# 'l' indicates it's a link
Hard links (without -s) create a direct reference to file data:
ln original.txt hardlink.txt
Hard links are less common because they have limitations (canβt span filesystems, canβt link directories).
Identifying File Types
file mysterious_file
Determines what type of file something is, regardless of its extension (or lack thereof):
$ file script
script: POSIX shell script, ASCII text executable
$ file image.jpg
image.jpg: JPEG image data, JFIF standard 1.01
$ file compiled_program
compiled_program: ELF 64-bit LSB executable, x86-64
Why this matters: Unix doesnβt rely on file extensions like Windows does. A file named document could be a text file, an image, or a program. The file command examines the actual content to tell you what it is.
Verifying File Integrity
md5sum filename
sha256sum filename
These commands generate cryptographic βfingerprintsβ (checksums) of files:
$ sha256sum ubuntu-22.04.iso
b8f31413336b9393ad5d8ef0282717b2ab19f007df2e9ed5196c13d8f9153c8b ubuntu-22.04.iso
Use cases:
- Verify downloaded files havenβt been corrupted or tampered with
- Check if two files are identical without comparing them byte-by-byte
- Detect changes in files (checksums change if even one bit changes)
Verification workflow:
# Download a file and its checksum:
wget https://example.com/file.zip
wget https://example.com/file.zip.sha256
# Verify:
sha256sum -c file.zip.sha256
# Output: file.zip: OK (means it matches)
4. Reading and Viewing Files
Quick Output: cat
cat filename.txt
Concatenate dumps the entire contents of a file to your screen instantly. Perfect for short files or when you need to pipe content to another command.
Multiple files:
cat file1.txt file2.txt file3.txt # Shows all files in sequence
Combining files:
cat part1.txt part2.txt > complete.txt
β οΈ Common Mistake: Using cat on large files. If you accidentally run cat on a gigabyte-sized log file, your terminal will freeze while it tries to display millions of lines. Use less instead.
Quick tips:
cat -n: Number all linescat -A: Show all special characters (tabs, line endings, etc.)
Interactive Viewing: less
less large_file.log
A powerful pager for viewing files of any size. Unlike cat, it doesnβt load the entire file into memoryβyou can view gigabyte-sized files instantly.
Essential controls:
SpacebarorPageDown: Next pageborPageUp: Previous pageg: Jump to beginningG: Jump to end/search_term: Search forward?search_term: Search backwardn: Next search resultN: Previous search resultq: Quit
Why βlessβ is more:
The name is a play on an older program called more. The joke: βless is more than more,β meaning less has more features than more.
Pro tips:
less +F file.log # Start in "follow" mode (like tail -f)
# Press Ctrl+C to stop following, then navigate normally
First and Last Lines
head filename.txt # First 10 lines
tail filename.txt # Last 10 lines
Custom line counts:
head -n 50 access.log # First 50 lines
tail -n 100 error.log # Last 100 lines
The killer feature: tail -f
tail -f /var/log/syslog
The -f (follow) flag watches a file in real-time, displaying new lines as theyβre added. This is indispensable for:
- Monitoring live log files
- Watching build processes
- Debugging applications in real-time
Stop following: Press Ctrl+C
Pro tip: Follow multiple files simultaneously:
tail -f /var/log/nginx/access.log /var/log/nginx/error.log
Reverse Text: rev
rev filename.txt
Reverses each line character-by-character:
Input: Hello World
Output: dlroW olleH
Practical use? Honestly, itβs rarely used except for:
- Fun text manipulation
- Certain data processing tasks
- Reversing accidentally reversed text
The Universal Editor: vi/vim
vi filename.txt
Vi (and its improved version, Vim) is the most universally available text editorβpresent on virtually every Unix-like system. Even if it seems arcane at first, knowing vi basics is essential for system administration.
Bare minimum survival guide:
-
Opening:
vi filename -
Modes:
- Normal mode (default): For navigation and commands
- Insert mode: For typing text (press
ito enter) - Command mode: For saving/quitting (press
:to enter)
-
Basic workflow:
- Press
ito start inserting text - Type your content
- Press
Escto return to Normal mode - Type
:wqand pressEnterto write and quit
- Press
-
Emergency exit:
- If youβre stuck: Press
Escseveral times, then type:q!and pressEnter :q!quits without saving (overriding any warnings)
- If youβre stuck: Press
Why learn vi?
- Itβs the only editor guaranteed to be present on remote servers
- Itβs powerful once you overcome the initial learning curve
- Many modern IDEs offer vim keybindings because theyβre efficient
Alternatives if vi isnβt your thing:
nano: Simpler, more intuitive for beginnersemacs: Powerful but requires installation on some systems
5. Searching: Finding Files and Text
Searching Inside Files: grep
grep "search_term" filename.txt
Global Regular Expression Print is your text search workhorse. It scans files line-by-line and outputs matching lines.
Basic examples:
# Find error messages in a log:
grep "ERROR" application.log
# Case-insensitive search:
grep -i "warning" system.log # Matches WARNING, Warning, warning
# Show line numbers:
grep -n "TODO" script.sh
# Output: 42:# TODO: Fix this later
# Invert match (show lines that DON'T match):
grep -v "DEBUG" app.log # Hide debug messages
# Count matches:
grep -c "success" results.txt
# Output: 127
Recursive search through directories:
grep -r "config_value" /etc/
This searches through all files in /etc/ and its subdirectoriesβincredibly powerful for finding where a setting is defined.
Advanced options:
-A 3: Show 3 lines After each match (context)-B 3: Show 3 lines Before each match-C 3: Show 3 lines of Context (both before and after)-E: Use extended regular expressions (more powerful patterns)-w: Match whole words only-x: Match whole lines only (exact)
Real-world power move:
grep -rn "import pandas" ~/projects/ --include="*.py"
Find all Python files in your projects that import pandas, showing line numbers.
β οΈ Common Pitfall: Forgetting that grep returns an exit code. This matters in scripts:
if grep -q "error" log.txt; then
echo "Errors found!"
fi
The -q (quiet) flag suppresses outputβwe only care about the exit code.
Searching for Files: find
find /starting/path -name "pattern"
While grep searches inside files, find searches for files themselves based on name, size, type, permissions, modification time, and more.
Search by name:
# Find all .log files:
find /var/log -name "*.log"
# Case-insensitive name search:
find /home -iname "*.JPG" # Matches .jpg, .JPG, .Jpg, etc.
Search by type:
find /etc -type f # Only files
find /tmp -type d # Only directories
find /dev -type l # Only symbolic links
Search by time:
# Modified in last 7 days:
find . -mtime -7
# Modified more than 30 days ago:
find . -mtime +30
# Modified exactly 5 days ago:
find . -mtime 5
# Accessed in last 24 hours:
find /var/log -atime -1
Search by size:
# Files larger than 100MB:
find /home -size +100M
# Files smaller than 1KB:
find . -size -1k
# Files between 10MB and 50MB:
find . -size +10M -size -50M
Combining criteria (AND logic is default):
# Large log files modified recently:
find /var/log -name "*.log" -size +10M -mtime -7
Executing commands on found files:
# Delete all .tmp files:
find /tmp -name "*.tmp" -delete
# Change permissions on all scripts:
find ~/scripts -name "*.sh" -exec chmod +x {} \;
# More efficient with xargs (see Section 6):
find . -name "*.txt" -print0 | xargs -0 wc -l
β οΈ Warning: find with -delete or -exec rm is powerful and dangerous. Always test without the destructive action first:
# Test first:
find /tmp -name "*.tmp"
# If output looks right:
find /tmp -name "*.tmp" -delete
Pro tipβexcluding directories:
# Search but ignore node_modules:
find . -name "*.js" -not -path "*/node_modules/*"
Fast File Locating: locate
locate filename
Blazing fast filename search that works across your entire system. How? It searches a pre-built database instead of scanning the filesystem in real-time.
Advantages over find:
- Incredibly fast (sub-second searches across millions of files)
- Simple syntax
Disadvantages:
- Database may be outdated (usually updated daily)
- Only searches by filename (no size, time, or content filtering)
Updating the database:
sudo updatedb
Run this after creating or deleting many files if you need locate to find them immediately.
Case-insensitive search:
locate -i document.pdf
Limiting results:
locate -n 20 readme # Show only first 20 matches
When to use locate vs. find:
- Use
locatewhen you vaguely remember a filename and need quick results - Use
findwhen you need precise criteria (size, date, type) or the database might be stale
Finding Commands: apropos
apropos "search term"
Searches through man page descriptions to find relevant commands:
$ apropos "copy files"
cp (1) - copy files and directories
cpio (1) - copy files to and from archives
rsync (1) - fast, versatile, remote file-copying tool
Use case: βI need to do X, but I donβt know which commandβ¦β Just ask apropos.
Exact keyword match:
apropos -e networking
Comparing Files
Line-by-line comparison: diff
diff file1.txt file2.txt
Shows exactly what changed between two files:
3c3
< This is the old line
---
> This is the new line
7d6
< This line was deleted
Unified format (more readable):
diff -u file1.txt file2.txt
Side-by-side comparison:
diff -y file1.txt file2.txt
Comparing directories:
diff -r directory1/ directory2/
Practical use: Code reviews, configuration audits, troubleshooting changes.
Byte-by-byte comparison: cmp
cmp file1.bin file2.bin
Unlike diff (which compares text line-by-line), cmp compares files byte-by-byte. Essential for binary files like images, videos, or compiled programs.
Silent check (just the exit code):
cmp -s file1 file2 && echo "Files are identical"
Comparing sorted files: comm
comm file1.txt file2.txt
Requires both files to be sorted. Outputs three columns:
- Lines only in file1
- Lines only in file2
- Lines in both files
Suppress columns:
comm -12 file1.txt file2.txt # Show only lines in both (intersection)
comm -23 file1.txt file2.txt # Show only lines unique to file1
6. Advanced Text Processing: Power Tools
These commands transform raw text into structured information. Theyβre the secret sauce behind command-line productivity.
Stream Editor: sed
sed 's/old/new/' filename.txt
Stream Editor performs find-and-replace and other transformations as text flows through it.
Basic substitution:
# Replace first occurrence per line:
sed 's/cat/dog/' pets.txt
# Replace all occurrences (g for global):
sed 's/cat/dog/g' pets.txt
# Replace and save to new file:
sed 's/cat/dog/g' pets.txt > updated_pets.txt
# Edit file in-place:
sed -i 's/cat/dog/g' pets.txt
β οΈ Warning: -i modifies the original file. Use -i.bak to create a backup:
sed -i.bak 's/cat/dog/g' pets.txt # Creates pets.txt.bak
Delete lines:
# Delete line 5:
sed '5d' file.txt
# Delete lines 10-20:
sed '10,20d' file.txt
# Delete lines matching a pattern:
sed '/^#/d' script.sh # Remove comment lines
sed '/^$/d' file.txt # Remove blank lines
Print specific lines:
# Print line 42:
sed -n '42p' large_file.txt
# Print lines 10-20:
sed -n '10,20p' file.txt
Multiple operations:
sed -e 's/cat/dog/g' -e 's/red/blue/g' file.txt
Real-world exampleβconfiguration file update:
# Change database host in config:
sed -i 's/DB_HOST=localhost/DB_HOST=db.example.com/g' config.env
Pattern Scanner: awk
awk '{print $1}' file.txt
AWK is a complete programming language designed for text processing. Its superpower: effortlessly handling column-based data.
Understanding AWKβs model:
- AWK processes text line-by-line
- Each line is split into fields (columns)
$1is the first field,$2is the second, etc.$0is the entire line
Basic field extraction:
# Print first column:
ls -l | awk '{print $9}' # Filenames only
# Print multiple columns:
ls -l | awk '{print $9, $5}' # Filename and size
# Reorder columns:
echo "John Doe 30" | awk '{print $3, $1, $2}'
# Output: 30 John Doe
Custom field separators:
# Default separator is whitespace, but you can change it:
awk -F':' '{print $1}' /etc/passwd # Print all usernames
# Using comma as separator:
awk -F',' '{print $2}' data.csv
Conditional processing:
# Print lines where column 3 is greater than 100:
awk '$3 > 100' data.txt
# Print lines matching a pattern:
awk '/ERROR/ {print $1, $4}' log.txt
# Combine conditions:
awk '$3 > 100 && $5 == "active"' data.txt
Mathematical operations:
# Sum all numbers in column 2:
awk '{sum += $2} END {print sum}' numbers.txt
# Average:
awk '{sum += $1; count++} END {print sum/count}' data.txt
# Count lines:
awk 'END {print NR}' file.txt # NR = Number of Records (lines)
Real-world examples:
Analyze access logs:
# Count requests per IP:
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head
# Total bandwidth transferred (column 10 is bytes):
awk '{sum += $10} END {print sum/1024/1024 " MB"}' access.log
Parse CSV data:
# Extract email addresses from CSV:
awk -F',' '{print $3}' contacts.csv
# Filter high-value transactions:
awk -F',' '$4 > 1000 {print $1, $2, $4}' transactions.csv
Pro tip: AWK can replace many pipes:
# Instead of: cat file | grep pattern | awk '{print $2}'
# Just use:
awk '/pattern/ {print $2}' file
Simple Column Cutter: cut
cut -d',' -f1 data.csv
A simpler alternative to AWK for basic column extraction:
Extract specific fields:
# Field 1 (default delimiter is tab):
cut -f1 file.txt
# Fields 1 and 3:
cut -f1,3 file.txt
# Field range:
cut -f2-5 file.txt
# Custom delimiter:
cut -d':' -f1 /etc/passwd # Extract usernames
cut -d',' -f2,4 data.csv # Extract columns 2 and 4 from CSV
Character-based extraction:
# First 10 characters of each line:
cut -c1-10 file.txt
# Characters 5 through 15:
cut -c5-15 file.txt
# Everything from character 20 onward:
cut -c20- file.txt
When to use cut vs. awk:
- Use
cutfor simple, single-delimiter column extraction - Use
awkfor complex conditions, calculations, or multiple delimiters
Sorting Lines: sort
sort filename.txt
Arranges lines alphabetically or numerically:
Basic sorting:
# Alphabetical (default):
sort names.txt
# Reverse order:
sort -r names.txt
# Numeric sort (critical for numbers):
sort -n numbers.txt
Why -n matters:
# Without -n (alphabetical):
echo -e "1\n10\n2\n20" | sort
# Output: 1, 10, 2, 20 (wrong!)
# With -n (numeric):
echo -e "1\n10\n2\n20" | sort -n
# Output: 1, 2, 10, 20 (correct!)
Sort by specific column:
# Sort by second column, numerically:
sort -k2 -n data.txt
# Sort by third column, reverse:
sort -k3 -r data.txt
# Multiple sort keys:
sort -k1,1 -k2n data.txt # Sort by column 1, then by column 2 numerically
Advanced options:
# Ignore leading blanks:
sort -b file.txt
# Case-insensitive:
sort -f names.txt
# Human-readable numbers (understands K, M, G):
du -h * | sort -h
# Random shuffle:
sort -R file.txt
# Unique sort (remove duplicates while sorting):
sort -u file.txt
Real-world exampleβfind largest directories:
du -sh * | sort -h | tail -10
Remove Duplicate Lines: uniq
uniq file.txt
Removes adjacent duplicate linesβthis is crucial to understand.
β οΈ Critical Pitfall: uniq only removes duplicates that are next to each other:
# This WON'T work as expected:
echo -e "apple\nbanana\napple" | uniq
# Output: apple, banana, apple (duplicate remains!)
# This WILL work:
echo -e "apple\nbanana\napple" | sort | uniq
# Output: apple, banana
Best practice: Always pipe through sort first:
sort file.txt | uniq
Count occurrences:
sort file.txt | uniq -c
# Output:
# 3 apple
# 1 banana
# 2 cherry
Show only duplicates:
sort file.txt | uniq -d
Show only unique lines (no duplicates):
sort file.txt | uniq -u
Real-world examples:
Count unique visitors in access log:
awk '{print $1}' access.log | sort | uniq | wc -l
Find most common error messages:
grep ERROR app.log | sort | uniq -c | sort -nr | head -10
Character Translation: tr
tr 'abc' 'xyz'
Translates or deletes charactersβworks on standard input only:
Character substitution:
# Convert lowercase to uppercase:
echo "hello world" | tr 'a-z' 'A-Z'
# Output: HELLO WORLD
# Convert uppercase to lowercase:
echo "HELLO WORLD" | tr 'A-Z' 'a-z'
# Output: hello world
# ROT13 encoding:
echo "Hello" | tr 'A-Za-z' 'N-ZA-Mn-za-m'
Delete characters:
# Remove all digits:
echo "Phone: 555-1234" | tr -d '0-9'
# Output: Phone: -
# Remove all spaces:
echo "too many spaces" | tr -d ' '
# Output: toomanyspaces
# Remove newlines:
cat multiline.txt | tr -d '\n'
Squeeze repeated characters:
# Collapse multiple spaces to single space:
echo "too many spaces" | tr -s ' '
# Output: too many spaces
# Remove duplicate letters:
echo "bookkeeper" | tr -s 'a-z'
# Output: bokeper
Complement (invert the set):
# Keep only alphanumeric characters:
echo "Hello, World! 123" | tr -cd 'A-Za-z0-9'
# Output: HelloWorld123
# Remove everything except newlines (one word per line):
cat file.txt | tr -cs 'A-Za-z' '\n'
Real-world uses:
Convert DOS line endings to Unix:
tr -d '\r' < dos_file.txt > unix_file.txt
Generate random passwords:
tr -dc 'A-Za-z0-9!@#$%' < /dev/urandom | head -c 20
Word, Line, and Byte Counting: wc
wc filename.txt
Word Count provides statistics about text:
Default output:
$ wc document.txt
45 312 2048 document.txt
β β β ββ filename
β β βββββββ bytes
β βββββββββββ words
βββββββββββββββ lines
Specific counts:
wc -l file.txt # Lines only (most common)
wc -w file.txt # Words only
wc -c file.txt # Bytes only
wc -m file.txt # Characters (may differ from bytes with Unicode)
wc -L file.txt # Length of longest line
Multiple files:
$ wc -l *.txt
100 file1.txt
200 file2.txt
150 file3.txt
450 total
Real-world examples:
Count files in directory:
ls | wc -l
Count lines of code in project:
find . -name "*.py" -exec cat {} \; | wc -l
Monitor log growth rate:
# Before:
wc -l app.log
# ... wait some time ...
# After:
wc -l app.log # Compare the numbers
Count occurrences of a pattern:
grep -r "TODO" src/ | wc -l
Pipe Splitter: tee
command | tee output.txt
Splits a pipeline: sends output to both a file and the screen (or next command).
Basic usage:
# See output AND save it:
ls -la | tee file_list.txt
# Long-running commandβmonitor and save:
./build_script.sh | tee build.log
Append instead of overwrite:
echo "New entry" | tee -a log.txt
Multiple outputs:
echo "Important" | tee file1.txt file2.txt file3.txt
Combining with sudo:
# This WON'T work (sudo doesn't apply to redirection):
sudo echo "nameserver 8.8.8.8" > /etc/resolv.conf
# This WILL work:
echo "nameserver 8.8.8.8" | sudo tee /etc/resolv.conf
# Append with sudo:
echo "option timeout:1" | sudo tee -a /etc/resolv.conf
Real-world patternβsave and continue processing:
# Save intermediate results while continuing pipeline:
cat data.txt | tee raw_data.txt | grep "ERROR" | tee errors.txt | wc -l
Pro tipβsilent output:
# Save to file without screen output:
command | tee file.txt > /dev/null
Argument Builder: xargs
command1 | xargs command2
Converts input into arguments for another command. This solves a fundamental problem: many commands donβt read from standard inputβthey need arguments.
The problem xargs solves:
# This doesn't work (rm doesn't read filenames from stdin):
find . -name "*.tmp" | rm
# This works:
find . -name "*.tmp" | xargs rm
Basic usage:
# Delete files returned by find:
find . -name "*.log" | xargs rm
# Create directories:
echo "dir1 dir2 dir3" | xargs mkdir
# Download multiple URLs:
cat urls.txt | xargs wget
Handling spaces and special characters:
# UNSAFE (breaks with spaces in filenames):
find . -name "*.txt" | xargs rm
# SAFE (use null delimiter):
find . -name "*.txt" -print0 | xargs -0 rm
The -print0 and -0 combination uses null bytes (\0) as delimiters instead of spaces, making it safe for filenames with spaces, quotes, or other special characters.
Control execution:
# Run command once per item (-n 1):
echo "file1 file2 file3" | xargs -n 1 echo "Processing:"
# Output:
# Processing: file1
# Processing: file2
# Processing: file3
# Parallel execution (-P):
find . -name "*.jpg" | xargs -P 4 -I {} convert {} {}.optimized.jpg
# Processes 4 images simultaneously
Interactive prompting:
# Confirm before each execution:
find . -name "*.tmp" | xargs -p rm
# Prompts: rm ./file1.tmp?...
Replace string:
# Use {} as placeholder:
find . -name "*.txt" | xargs -I {} cp {} {}.backup
# Custom placeholder:
cat hostnames.txt | xargs -I HOST ssh HOST "df -h"
Real-world examples:
Batch rename files:
ls *.jpeg | xargs -I {} bash -c 'mv {} $(echo {} | sed s/jpeg/jpg/)'
Check which servers are up:
cat servers.txt | xargs -I {} -P 10 ping -c 1 {}
Find and replace across multiple files:
grep -l "old_term" *.txt | xargs sed -i 's/old_term/new_term/g'
Compress large files in parallel:
find . -name "*.log" -size +100M -print0 | xargs -0 -P 4 gzip
7. Users, Permissions, and Access Control
Linux is a multi-user system with robust permission controls. Understanding these concepts is essential for both security and day-to-day operations.
Identifying Yourself
whoami
Shows your current username:
$ whoami
akib
When it matters: After using su to switch users, or in scripts where you need to check whoβs running the code.
Detailed User Information
id
Displays your user ID (UID), group ID (GID), and all group memberships:
$ id
uid=1000(akib) gid=1000(akib) groups=1000(akib),27(sudo),998(docker)
What this tells you:
uid=1000(akib): Your user ID is 1000, username is βakibβgid=1000(akib): Your primary group ID is 1000, group name is βakibβgroups=...: Youβre also in the βsudoβ and βdockerβ groups
Why it matters: Group membership determines what you can access. Being in the βsudoβ group means you can run admin commands. Being in the βdockerβ group means you can run Docker containers without sudo.
Check another user:
id username
List Group Memberships
groups
Simpler than idβjust lists group names:
$ groups
akib sudo docker www-data
Check another userβs groups:
groups username
Execute as Administrator: sudo
sudo command
Superuser Do lets you run individual commands with root privileges:
# Install software:
sudo apt install nginx
# Edit system files:
sudo nano /etc/hosts
# Restart services:
sudo systemctl restart apache2
# View protected files:
sudo cat /var/log/auth.log
How it works:
- You enter your password (not rootβs password)
- System checks if youβre in the
sudogroup - Command runs with root privileges
- Your password is cached for ~15 minutes
Running multiple commands:
# Start a root shell:
sudo -i # Login shell (loads root's environment)
sudo -s # Shell (preserves your environment)
# Run specific shell as root:
sudo bash
Run as different user:
sudo -u username command
Preserve environment variables:
sudo -E command # Keeps your environment
Best practices:
- Only use
sudowhen necessary - Never run untrusted scripts with
sudo - Review what a command does before adding
sudo - Use
sudo -ifor multiple admin tasks, thenexitwhen done
β οΈ Security Warning: The phrase βwith great power comes great responsibilityβ was practically invented for sudo. One mistyped command can destroy your system.
Switch Users: su
su username
Substitute User switches your entire session to another account:
# Become root:
su
# or
su root
# Become another user:
su - john # The dash loads john's environment
Difference from sudo:
surequires the target userβs passwordsudorequires your passwordsuswitches your entire sessionsudoruns one command
Why sudo is preferred:
- More auditable (logs show who did what)
- More granular (can limit what commands users can run)
- Doesnβt require sharing the root password
- Automatically times out
Return to original user:
exit
Understanding File Permissions
Every file and directory has permissions that control who can read, write, or execute it.
Viewing permissions:
$ ls -l script.sh
-rwxr-xr-- 1 akib developers 2048 Oct 24 10:30 script.sh
βββββββββ
βββββββββ
βββββββββ΄β Other users: r-- (read only)
βββββββββββ Group: r-x (read and execute)
βββββββββββ Owner: rwx (read, write, execute)
βββββββββββ ACLs indicator
βββββββββββ Number of hard links
βββββββββββ File type: - (regular file)
βββββββββββ Also applies to: d (directory), l (link)
Permission breakdown:
- r (read): View file contents / List directory contents
- w (write): Modify file / Create/delete files in directory
- x (execute): Run file as program / Enter directory
Three permission sets:
- Owner (user who created the file)
- Group (users in the fileβs group)
- Others (everyone else)
Changing Permissions: chmod
chmod permissions file
Symbolic method (human-readable):
# Add execute permission for owner:
chmod u+x script.sh
# Remove write permission for others:
chmod o-w document.txt
# Add read permission for group:
chmod g+r data.txt
# Set exact permissions:
chmod u=rwx,g=rx,o=r file.txt
# Multiple changes:
chmod u+x,g+x,o-w script.sh
Symbols:
u= user (owner)g= groupo= othersa= all (user, group, and others)
Operators:
+= add permission-= remove permission== set exact permission
Octal method (numeric):
Each permission set is represented by a three-digit octal number:
r = 4
w = 2
x = 1
Add them up:
7(4+2+1) = rwx6(4+2) = rw-5(4+1) = r-x4= rβ0= β
Common patterns:
# rwxr-xr-x (755): Owner full, others read/execute
chmod 755 script.sh
# rw-r--r-- (644): Owner read/write, others read-only
chmod 644 document.txt
# rwx------ (700): Only owner can access
chmod 700 private_script.sh
# rw-rw-r-- (664): Owner and group can edit, others read
chmod 664 shared_doc.txt
Recursive (apply to all files in directory):
chmod -R 755 /var/www/html/
Real-world examples:
Make script executable:
chmod +x deploy.sh
./deploy.sh # Now you can run it
Secure SSH keys:
chmod 600 ~/.ssh/id_rsa # Private keys must be owner-only
chmod 644 ~/.ssh/id_rsa.pub # Public keys can be readable
Fix web server permissions:
# Directories: 755 (browsable)
find /var/www -type d -exec chmod 755 {} \;
# Files: 644 (readable)
find /var/www -type f -exec chmod 644 {} \;
Changing Ownership: chown
chown owner:group file
Changes who owns a file:
# Change owner only:
sudo chown john file.txt
# Change owner and group:
sudo chown john:developers file.txt
# Change group only:
sudo chown :developers file.txt
# or use chgrp:
sudo chgrp developers file.txt
# Recursive:
sudo chown -R www-data:www-data /var/www/html/
Why you need sudo: Only root can change file ownership (security feature).
Real-world use case: After extracting files as root, change ownership to regular user:
sudo tar -xzf archive.tar.gz
sudo chown -R $USER:$USER extracted_folder/
Fix web application permissions:
# Web server needs to own web files:
sudo chown -R www-data:www-data /var/www/myapp/
# But you need to edit them:
sudo usermod -aG www-data $USER # Add yourself to www-data group
Changing Your Password
passwd
Prompts you to change your password:
$ passwd
Changing password for akib.
Current password:
New password:
Retype new password:
passwd: password updated successfully
Change another userβs password (as root):
sudo passwd username
Password requirements:
- Usually minimum 8 characters
- Mix of letters, numbers, symbols
- Not based on dictionary words
- Different from previous passwords
Best practices:
- Use a password manager
- Use strong, unique passwords for each system
- Enable two-factor authentication when available
- Change passwords periodically, especially after security incidents
8. Process and System Management
Understanding and controlling what your system is doing.
Viewing Processes: ps
ps
Process Status shows currently running processes:
Basic output:
$ ps
PID TTY TIME CMD
1234 pts/0 00:00:00 bash
5678 pts/0 00:00:00 ps
Show all processes:
ps aux # BSD style (no dash)
ps -ef # Unix style (with dash)
Both show similar informationβchoose whichever you prefer.
Understanding ps aux output:
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
akib 1234 0.5 2.1 123456 12345 pts/0 S 10:30 0:05 python app.py
β β β β β β β β β β ββ command
β β β β β β β β β βββββββ CPU time used
β β β β β β β β βββββββββββββββ start time
β β β β β β β ββββββββββββββββββββ state
β β β β β β βββββββββββββββββββββββββ terminal
β β β β β ββββββββββββββββββββββββββββββ resident memory (KB)
β β β β βββββββββββββββββββββββββββββββββββββ virtual memory (KB)
β β β βββββββββββββββββββββββββββββββββββββββββββ % of RAM
β β ββββββββββββββββββββββββββββββββββββββββββββββββ % of CPU
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββ process ID
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ user
Process states:
R: RunningS: Sleeping (waiting for an event)D: Uninterruptible sleep (usually I/O)Z: Zombie (finished but not cleaned up)T: Stopped (paused)
Find specific processes:
ps aux | grep python
ps aux | grep -i apache
Show process tree (parent-child relationships):
ps auxf # Forest view
pstree # Dedicated tree view
Sort by CPU usage:
ps aux --sort=-%cpu | head
Sort by memory usage:
ps aux --sort=-%mem | head
Real-Time Process Monitoring: top and htop
top
Interactive, real-time view of system processes:
Essential top commands:
q: Quitk: Kill a process (prompts for PID)M: Sort by memory usageP: Sort by CPU usage1: Show individual CPU coresh: Helpu: Filter by usernameSpacebar: Refresh immediately
Understanding the top display:
top - 14:32:01 up 5 days, 2:17, 3 users, load average: 0.45, 0.62, 0.58
Tasks: 187 total, 1 running, 186 sleeping, 0 stopped, 0 zombie
%Cpu(s): 12.3 us, 3.1 sy, 0.0 ni, 84.1 id, 0.5 wa, 0.0 hi, 0.0 si, 0.0 st
MiB Mem: 15842.5 total, 2341.2 free, 8234.7 used, 5266.6 buff/cache
MiB Swap: 2048.0 total, 2048.0 free, 0.0 used. 6892.4 avail Mem
Load average explained:
- Three numbers: 1-minute, 5-minute, 15-minute averages
- Represents number of processes waiting for CPU time
- On a 4-core system, load of 4.0 means fully utilized
- Load > number of cores = system is overloaded
Better alternative: htop
htop
A more user-friendly version with:
- Color-coded display
- Mouse support
- Easier process killing
- Tree view by default
- Better visual representation of CPU and memory
Install htop:
sudo apt install htop # Debian/Ubuntu
sudo yum install htop # Red Hat/CentOS
β οΈ Common Mistake: Panicking when you see high CPU usage in top. Check if itβs legitimate activity before killing processes.
Terminating Processes: kill
kill PID
Sends signals to processesβusually to terminate them:
Basic usage:
# Graceful termination (SIGTERM):
kill 1234
# Force kill (SIGKILL):
kill -9 1234
Signal types:
SIGTERM(15, default): βPlease terminate gracefullyβ- Allows process to clean up (save files, close connections)
- Can be ignored by the process
SIGKILL(9): βDie immediatelyβ- Cannot be ignored or caught
- No cleanupβdata loss possible
- Use as last resort
Other useful signals:
kill -HUP 1234 # Hang up (often makes daemons reload config)
kill -STOP 1234 # Pause process
kill -CONT 1234 # Resume paused process
Kill by name:
killall process_name # Kill all processes with this name
pkill pattern # Kill processes matching pattern
Examples:
# Kill all Python processes:
killall python3
# Kill all processes owned by user:
pkill -u username
# Kill frozen Firefox:
killall -9 firefox
Finding the PID:
# Method 1:
ps aux | grep program_name
# Method 2:
pgrep program_name
# Method 3:
pidof program_name
β οΈ Warning: Always try regular kill before kill -9. Forcing termination can lead to:
- Lost unsaved work
- Corrupted files
- Orphaned processes
- Resource leaks
Job Control: bg, fg, jobs
When you start a program from the terminal, itβs a βforeground jobβ that takes over your prompt. Job control lets you manage multiple programs.
Suspend current job:
Press Ctrl+Z to pause the foreground job:
$ python long_script.py
^Z
[1]+ Stopped python long_script.py
List jobs:
$ jobs
[1]+ Stopped python long_script.py
[2]- Running npm start &
Resume in foreground:
fg %1 # Resume job 1 in foreground
Resume in background:
bg %1 # Job 1 continues running, but you get your prompt back
Start job in background immediately:
long_running_command & # Ampersand runs it in background
Real-world workflow:
# Start editing a file:
vim document.txt
# Realize you need to check something:
# Press Ctrl+Z to suspend vim
# Run other commands:
ls -la
cat other_file.txt
# Go back to editing:
fg
# Or start a long task while editing:
bg # Continue vim in background (if it supports it)
β οΈ Limitation: Background jobs still output to the terminal. For true detachment, use nohup or terminal multiplexers.
Run After Logout: nohup
nohup command &
No Hang Up makes a process immune to logoutβessential for long-running tasks on remote servers:
# Start a long backup:
nohup ./backup_script.sh &
# Start a development server:
nohup npm start &
# Output goes to nohup.out by default:
tail -f nohup.out
Redirect output:
nohup ./script.sh > output.log 2>&1 &
Explanation:
nohup: Ignore hangup signals> output.log: Redirect stdout2>&1: Redirect stderr to same place as stdout&: Run in background
Check if itβs running:
ps aux | grep script.sh
Better alternative for remote work: Use tmux or screen (see Advanced Techniques section).
Disk Space: df
df -h
Disk Free shows available disk space per filesystem:
$ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 50G 35G 13G 74% /
/dev/sdb1 500G 350G 125G 74% /home
tmpfs 7.8G 1.2M 7.8G 1% /dev/shm
What it shows:
Filesystem: Device or partitionSize: Total capacityUsed: Space consumedAvail: Space remainingUse%: Percentage fullMounted on: Where itβs accessible in the directory tree
β οΈ Warning: When a disk hits 100%, things break:
- Canβt save files
- Logs canβt write (applications fail)
- System becomes unstable
Quick checks:
df -h / # Check root partition
df -h /home # Check home partition
df -h --total # Show grand total
Find largest filesystems:
df -h | sort -h -k3 # Sort by usage
Directory Sizes: du
du -sh directory/
Disk Usage shows how much space files and directories consume:
# Summary of directory:
du -sh ~/Downloads/
# Output: 2.3G /home/akib/Downloads/
# Summarize each subdirectory:
du -sh ~/Documents/*
# Output:
# 150M /home/akib/Documents/Work
# 3.2G /home/akib/Documents/Projects
# 45M /home/akib/Documents/Personal
# Show all files and directories (recursive):
du -h ~/Projects/
Options:
-s: Summary (donβt show subdirectories)-h: Human-readable sizes-c: Show grand total--max-depth=N: Limit recursion depth
Find disk hogs:
# Top 10 largest directories:
du -sh /* | sort -h | tail -10
# Or more accurate:
du -h --max-depth=1 / | sort -h | tail -10
Find large files:
find / -type f -size +100M -exec du -h {} \; | sort -h
Real-world troubleshooting:
# "Disk full" alertβfind the culprit:
du -sh /* | sort -h | tail -5
# Drill down into the largest directory:
du -sh /var/* | sort -h | tail -5
# Continue until you find the problem:
du -sh /var/log/* | sort -h | tail -5
System Information: uname
uname -a
Shows kernel and system information:
$ uname -a
Linux myserver 5.15.0-56-generic #62-Ubuntu SMP Thu Nov 24 13:31:22 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
Individual components:
uname -s # Kernel name: Linux
uname -n # Network name: myserver
uname -r # Kernel release: 5.15.0-56-generic
uname -v # Kernel version: #62-Ubuntu SMP Thu Nov 24...
uname -m # Machine hardware: x86_64
uname -o # Operating system: GNU/Linux
Practical use:
# Check if you're on 64-bit:
uname -m
# x86_64 = 64-bit, i686 = 32-bit
# Get kernel version for bug reports:
uname -r
Hostname
hostname
Shows or sets the systemβs network name:
$ hostname
myserver.example.com
# Show just the short name:
$ hostname -s
myserver
# Show IP addresses:
$ hostname -I
192.168.1.100 10.0.0.50
Change hostname (temporary):
sudo hostname newname
Change hostname (permanent):
# Ubuntu/Debian:
sudo hostnamectl set-hostname newname
# Older systems:
sudo nano /etc/hostname # Edit file
sudo nano /etc/hosts # Update 127.0.1.1 entry
System Shutdown and Reboot
reboot
shutdown
Control system power state (requires sudo):
Reboot immediately:
sudo reboot
Shutdown immediately:
sudo shutdown -h now
Shutdown with delay:
sudo shutdown -h +10 # Shutdown in 10 minutes
sudo shutdown -h 23:00 # Shutdown at 11 PM
Reboot with delay:
sudo shutdown -r +5 # Reboot in 5 minutes
Cancel scheduled shutdown:
sudo shutdown -c
Broadcast message to users:
sudo shutdown -h +10 "System maintenance in 10 minutes"
Alternative commands:
sudo poweroff # Immediate shutdown
sudo halt # Stop the system (older method)
sudo init 0 # Shutdown (runlevel 0)
sudo init 6 # Reboot (runlevel 6)
9. Networking Essentials
Testing Connectivity: ping
ping hostname
Checks if you can reach a remote host:
$ ping google.com
PING google.com (142.250.185.46) 56(84) bytes of data.
64 bytes from lga34s34-in-f14.1e100.net (142.250.185.46): icmp_seq=1 ttl=117 time=12.3 ms
64 bytes from lga34s34-in-f14.1e100.net (142.250.185.46): icmp_seq=2 ttl=117 time=11.8 ms
Understanding output:
64 bytes: Packet sizeicmp_seq: Packet sequence numberttl: Time To Live (hops remaining)time: Round-trip latency in milliseconds
Stop pinging:
Press Ctrl+C to stop. Youβll see statistics:
--- google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3005ms
rtt min/avg/max/mdev = 11.532/12.015/12.847/0.518 ms
Useful options:
# Send specific number of pings:
ping -c 4 google.com
# Set interval (1 second default):
ping -i 0.5 example.com # Ping every 0.5 seconds
# Flood ping (requires root):
sudo ping -f 192.168.1.1 # As fast as possible (testing)
# Set packet size:
ping -s 1000 example.com # 1000-byte packets
Troubleshooting scenarios:
No response:
$ ping 192.168.1.50
PING 192.168.1.50 (192.168.1.50) 56(84) bytes of data.
^C
--- 192.168.1.50 ping statistics ---
5 packets transmitted, 0 received, 100% packet loss
Causes: Host down, network unreachable, firewall blocking ICMP
High latency:
time=523 ms # Should be <50ms for LAN, <100ms for internet
Causes: Network congestion, bad connection, routing issues
Packet loss:
10 packets transmitted, 7 received, 30% packet loss
Causes: Weak WiFi, network congestion, failing hardware
Remote Access: ssh
ssh user@hostname
Secure Shell connects you to remote Linux systems securely:
Basic connection:
ssh akib@192.168.1.100
ssh admin@server.example.com
Custom port:
ssh -p 2222 user@hostname
Execute single command:
ssh user@server "df -h"
ssh user@server "systemctl status nginx"
X11 forwarding (run GUI apps remotely):
ssh -X user@server
# Then run GUI programsβthey display on your local screen
Verbose output (troubleshooting):
ssh -v user@server # Verbose
ssh -vvv user@server # Very verbose
SSH config file (~/.ssh/config):
Make connections easier:
Host myserver
HostName server.example.com
User akib
Port 22
IdentityFile ~/.ssh/id_rsa
Host prod
HostName 203.0.113.50
User admin
Port 2222
Now just type:
ssh myserver
ssh prod
Key-based authentication (covered in Advanced Techniques):
- More secure than passwords
- No password typing required
- Essential for automation
β οΈ Security Best Practices:
- Never use root account directly (use sudo instead)
- Disable password authentication (use keys only)
- Use non-standard ports
- Enable fail2ban to block brute-force attacks
- Keep SSH updated
File Synchronization: rsync
rsync source destination
Remote Sync is the Swiss Army knife of file copyingβefficient, powerful, and network-aware:
Basic local copy:
rsync -av source/ destination/
Essential options:
-a: Archive mode (preserves permissions, timestamps, symbolic links)-v: Verbose (show files being transferred)-z: Compress during transfer-h: Human-readable sizes-P: Show Progress + keep partial files
Best practice combination:
rsync -avzP source/ destination/
Remote copying:
# Upload to remote server:
rsync -avz /local/path/ user@server:/remote/path/
# Download from remote server:
rsync -avz user@server:/remote/path/ /local/path/
Important trailing slash behavior:
# With trailing slashβcopy CONTENTS:
rsync -av source/ destination/
# Result: destination contains files from source
# Without trailing slashβcopy DIRECTORY:
rsync -av source destination/
# Result: destination/source/ contains the files
Delete files in destination not in source:
rsync -av --delete source/ destination/
Dry run (preview what would happen):
rsync -avn --delete source/ destination/
# -n = dry run (no changes made)
Exclude files:
# Exclude pattern:
rsync -av --exclude '*.tmp' source/ dest/
# Multiple excludes:
rsync -av --exclude '*.log' --exclude 'node_modules/' source/ dest/
# Exclude file list:
rsync -av --exclude-from='exclude-list.txt' source/ dest/
Resume interrupted transfers:
rsync -avP source/ dest/ # -P enables partial file resumption
Real-world examples:
Backup entire home directory:
rsync -avzP --delete ~/ /mnt/backup/home/
Mirror website to remote server:
rsync -avz --delete /var/www/html/ user@webserver:/var/www/html/
Sync with bandwidth limit:
rsync -avz --bwlimit=1000 large-files/ user@server:/path/
# Limit to 1000 KB/s
Why rsync beats scp:
- Only transfers changed parts of files (delta transfer)
- Can resume interrupted transfers
- More options for filtering and control
- Better for large transfers or slow connections
Network Information: ip
ip addr show
Modern tool for viewing and configuring network interfaces (replaces older ifconfig):
Show all network interfaces:
$ ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP
inet 192.168.1.100/24 brd 192.168.1.255 scope global eth0
Abbreviated versions:
ip a # Short for 'ip addr show'
ip addr # Same thing
ip link show # Show link-layer information
ip link # Abbreviated
Show specific interface:
ip addr show eth0
ip addr show wlan0
Show routing table:
ip route show
# or
ip r
Show statistics:
ip -s link # Interface statistics (packets, errors)
Common tasks:
Add IP address (temporary):
sudo ip addr add 192.168.1.50/24 dev eth0
Remove IP address:
sudo ip addr del 192.168.1.50/24 dev eth0
Bring interface up/down:
sudo ip link set eth0 up
sudo ip link set eth0 down
β οΈ Note: Changes with ip are temporaryβtheyβre lost on reboot. Permanent changes require editing network configuration files (location varies by distribution).
Downloading Files: wget and curl
Both download files from the web, but with different philosophies:
wget: The Downloader
wget URL
Designed specifically for downloading files:
Basic download:
wget https://example.com/file.zip
Save with custom name:
wget -O custom_name.zip https://example.com/file.zip
Resume interrupted download:
wget -c https://example.com/large_file.iso
Download multiple files:
wget -i urls.txt # File containing list of URLs
Background download:
wget -b https://example.com/file.zip
tail -f wget-log # Monitor progress
Recursive download (mirror site):
wget -r -np -k https://example.com/docs/
# -r = recursive
# -np = no parent (don't go up in directory structure)
# -k = convert links for local viewing
Limit download speed:
wget --limit-rate=200k https://example.com/file.zip
Authentication:
wget --user=username --password=pass https://example.com/file.zip
curl: The Swiss Army Knife
curl URL
More versatileβcan handle uploads, APIs, and complex protocols:
Basic download (outputs to stdout):
curl https://example.com/file.txt
Save to file:
curl -o filename.txt https://example.com/file.txt
# or preserve remote filename:
curl -O https://example.com/file.txt
Follow redirects:
curl -L https://example.com/redirect
Show progress:
curl -# -O https://example.com/file.zip # Progress bar
API requests:
# GET request:
curl https://api.example.com/users
# POST request with data:
curl -X POST -d "name=John&email=john@example.com" https://api.example.com/users
# JSON POST:
curl -X POST -H "Content-Type: application/json" \
-d '{"name":"John","email":"john@example.com"}' \
https://api.example.com/users
# With authentication:
curl -u username:password https://api.example.com/data
Headers:
# Show response headers:
curl -i https://example.com
# Show only headers:
curl -I https://example.com
# Custom headers:
curl -H "Authorization: Bearer TOKEN" https://api.example.com/data
Upload files:
curl -F "file=@document.pdf" https://example.com/upload
When to use which:
- wget: Downloading files, mirroring websites, resume capability
- curl: API testing, complex requests, headers, uploads
10. Archives and Compression
The Tape Archive: tar
tar options archive.tar files
Originally designed for Tape Archives, tar bundles multiple files into a single file (without compression):
Essential operations:
Create archive:
tar -cvf archive.tar file1 file2 directory/
# -c = create
# -v = verbose
# -f = filename
Extract archive:
tar -xvf archive.tar
# -x = extract
List contents:
tar -tvf archive.tar
# -t = list
Compressed archives:
Most tar archives are also compressed. The flag indicates compression type:
Gzip (.tar.gz or .tgz):
# Create:
tar -czvf archive.tar.gz directory/
# -z = gzip compression
# Extract:
tar -xzvf archive.tar.gz
# Extract to specific directory:
tar -xzvf archive.tar.gz -C /target/directory/
Bzip2 (.tar.bz2):
# Create (better compression, slower):
tar -cjvf archive.tar.bz2 directory/
# -j = bzip2 compression
# Extract:
tar -xjvf archive.tar.bz2
XZ (.tar.xz):
# Create (best compression, slowest):
tar -cJvf archive.tar.xz directory/
# -J = xz compression
# Extract:
tar -xJvf archive.tar.xz
Advanced options:
Exclude files:
tar -czvf backup.tar.gz --exclude='*.tmp' --exclude='node_modules' ~/project/
Extract specific files:
tar -xzvf archive.tar.gz path/to/specific/file
Preserve permissions:
tar -cpzvf archive.tar.gz directory/
# -p = preserve permissions
Append to existing archive:
tar -rvf archive.tar newfile.txt
# -r = append
Update archive (only newer files):
tar -uvf archive.tar directory/
# -u = update
Mnemonic for remembering flags:
- Create: Create Zipped File β
-czf - Extract: eXtract Zipped File β
-xzf - List: Table of Verbose Files β
-tvf
Real-world examples:
Backup home directory:
tar -czvf home-backup-$(date +%Y%m%d).tar.gz ~/
Backup with progress indicator:
tar -czvf backup.tar.gz directory/ --checkpoint=1000 --checkpoint-action=dot
Remote backup over SSH:
tar -czvf - directory/ | ssh user@server "cat > backup.tar.gz"
Extract while preserving everything:
sudo tar -xzvpf backup.tar.gz -C /
# -p = preserve permissions
# -C / = extract to root
Compression Tools
gzip/gunzip
gzip file.txt # Compresses to file.txt.gz (deletes original)
gunzip file.txt.gz # Decompresses (deletes .gz)
Keep original:
gzip -k file.txt
gunzip -k file.txt.gz
Compression levels:
gzip -1 file.txt # Fastest, least compression
gzip -9 file.txt # Slowest, best compression
View compressed file without extracting:
zcat file.txt.gz # View contents
zless file.txt.gz # View with pager
zgrep pattern file.txt.gz # Search compressed file
bzip2/bunzip2
bzip2 file.txt # Better compression than gzip
bunzip2 file.txt.bz2
Similar options to gzip (-k to keep, -1 to -9 for levels).
View compressed:
bzcat file.txt.bz2
bzless file.txt.bz2
zip/unzip
zip archive.zip file1 file2 directory/
unzip archive.zip
ZIP format (compatible with Windows):
Create archive:
# Files:
zip archive.zip file1.txt file2.txt
# Directories (recursive):
zip -r archive.zip directory/
# With compression level:
zip -9 -r archive.zip directory/ # Maximum compression
Extract archive:
# Current directory:
unzip archive.zip
# Specific directory:
unzip archive.zip -d /target/directory/
# List contents without extracting:
unzip -l archive.zip
# Extract specific file:
unzip archive.zip path/to/file.txt
Update existing archive:
zip -u archive.zip newfile.txt
Delete from archive:
zip -d archive.zip file-to-remove.txt
Password protection:
zip -e -r secure.zip directory/ # Prompts for password
unzip secure.zip # Prompts for password
11. Bash Scripting: Automating Tasks
Bash isnβt just an interactive shellβitβs a complete programming language for automation.
Script Basics
Create a script:
#!/bin/bash
# This is a comment
echo "Hello, World!"
Make it executable:
chmod +x script.sh
Run it:
./script.sh
The shebang: #!/bin/bash tells the system which interpreter to use.
Variables
Assignment:
name="John"
count=42
path="/home/user"
β οΈ Critical: No spaces around =
name="John" # Correct
name = "John" # Wrong! This runs 'name' as a command
Using variables:
echo "Hello, $name"
echo "Count is: $count"
echo "Path: ${path}/documents" # Curly braces when needed
Command substitution:
current_date=$(date +%Y-%m-%d)
file_count=$(ls | wc -l)
user=$(whoami)
echo "Today is $current_date"
echo "You are $user"
Reading user input:
echo "Enter your name:"
read name
echo "Hello, $name!"
# Read with prompt:
read -p "Enter your age: " age
# Silent input (passwords):
read -sp "Enter password: " password
Environment variables:
echo $HOME # /home/username
echo $USER # username
echo $PATH # Executable search path
echo $PWD # Present working directory
echo $SHELL # Current shell
Special Parameters
$0 # Script name
$1 # First argument
$2 # Second argument
$9 # Ninth argument
${10} # Tenth argument (braces required for >9)
$@ # All arguments as separate strings
$* # All arguments as single string
$# # Number of arguments
$$ # Current process ID
$? # Exit code of last command
Example script:
#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "All arguments: $@"
echo "Number of arguments: $#"
Usage:
$ ./script.sh apple banana cherry
Script name: ./script.sh
First argument: apple
All arguments: apple banana cherry
Number of arguments: 3
Exit Codes
Every command returns an exit code:
0= Success- Non-zero = Error
# Check last command's exit code:
ls /existing/directory
echo $? # Output: 0
ls /nonexistent/directory
echo $? # Output: 2 (error code)
Using in scripts:
#!/bin/bash
if cp source.txt dest.txt; then
echo "Copy successful"
else
echo "Copy failed"
exit 1 # Exit script with error code
fi
String Manipulation
text="Hello World"
# Length:
echo ${#text} # 11
# Substring (position:length):
echo ${text:0:5} # Hello
echo ${text:6} # World
# Replace first occurrence:
echo ${text/World/Universe} # Hello Universe
# Replace all occurrences:
fruit="apple apple apple"
echo ${fruit//apple/orange} # orange orange orange
# Remove prefix:
path="/home/user/document.txt"
echo ${path#*/} # home/user/document.txt (shortest match)
echo ${path##*/} # document.txt (longest match - basename)
# Remove suffix:
file="document.txt.backup"
echo ${file%.*} # document.txt (shortest match)
echo ${file%%.*} # document (longest match)
# Uppercase/Lowercase:
text="Hello"
echo ${text^^} # HELLO
echo ${text,,} # hello
Conditional Statements
if [[ condition ]]; then
# commands
elif [[ another_condition ]]; then
# commands
else
# commands
fi
File tests:
if [[ -e "/path/to/file" ]]; then
echo "File exists"
fi
if [[ -f "document.txt" ]]; then
echo "It's a regular file"
fi
if [[ -d "/home/user" ]]; then
echo "It's a directory"
fi
if [[ -r "file.txt" ]]; then
echo "File is readable"
fi
if [[ -w "file.txt" ]]; then
echo "File is writable"
fi
if [[ -x "script.sh" ]]; then
echo "File is executable"
fi
if [[ -s "file.txt" ]]; then
echo "File is not empty"
fi
String comparisons:
if [[ "$USER" == "akib" ]]; then
echo "Welcome, Akib"
fi
if [[ "$name" != "admin" ]]; then
echo "Not admin"
fi
if [[ -z "$variable" ]]; then
echo "Variable is empty"
fi
if [[ -n "$variable" ]]; then
echo "Variable is not empty"
fi
Numeric comparisons:
if [[ $count -eq 10 ]]; then
echo "Count is 10"
fi
if [[ $age -gt 18 ]]; then
echo "Adult"
fi
if [[ $num -lt 100 ]]; then
echo "Less than 100"
fi
if [[ $value -ge 50 ]]; then
echo "50 or more"
fi
if [[ $score -le 100 ]]; then
echo "100 or less"
fi
if [[ $result -ne 0 ]]; then
echo "Non-zero result"
fi
Logical operators:
# AND:
if [[ $age -gt 18 && $age -lt 65 ]]; then
echo "Working age"
fi
# OR:
if [[ "$user" == "admin" || "$user" == "root" ]]; then
echo "Privileged user"
fi
# NOT:
if [[ ! -f "config.txt" ]]; then
echo "Config file missing"
fi
Loops
For Loop
# Iterate over list:
for item in apple banana cherry; do
echo "Fruit: $item"
done
# Iterate over files:
for file in *.txt; do
echo "Processing $file"
# Do something with $file
done
# Iterate over command output:
for user in $(cat users.txt); do
echo "Creating account for $user"
done
# C-style loop:
for ((i=1; i<=10; i++)); do
echo "Number: $i"
done
# Range:
for i in {1..10}; do
echo $i
done
# Range with step:
for i in {0..100..10}; do
echo $i # 0, 10, 20, ..., 100
done
While Loop
# Basic while:
count=1
while [[ $count -le 5 ]]; do
echo "Count: $count"
((count++))
done
# Read file line by line:
while read -r line; do
echo "Line: $line"
done < input.txt
# Infinite loop:
while true; do
echo "Running..."
sleep 1
done
# Until loop (opposite of while):
count=1
until [[ $count -gt 5 ]]; do
echo "Count: $count"
((count++))
done
Functions
# Define function:
function greet() {
echo "Hello, $1!"
}
# Or without 'function' keyword:
greet() {
echo "Hello, $1!"
}
# Call function:
greet "World" # Output: Hello, World!
# With return value:
add() {
local result=$(($1 + $2))
echo $result
}
sum=$(add 5 3)
echo "Sum: $sum" # Sum: 8
# With explicit return code:
check_file() {
if [[ -f "$1" ]]; then
return 0 # Success
else
return 1 # Failure
fi
}
if check_file "document.txt"; then
echo "File exists"
fi
Arrays
# Create array:
fruits=("apple" "banana" "cherry")
# Access elements:
echo ${fruits[0]} # apple
echo ${fruits[1]} # banana
# All elements:
echo ${fruits[@]} # apple banana cherry
# Array length:
echo ${#fruits[@]} # 3
# Add element:
fruits+=("date")
# Loop through array:
for fruit in "${fruits[@]}"; do
echo $fruit
done
# Associative arrays (like dictionaries):
declare -A person
person[name]="John"
person[age]=30
person[city]="New York"
echo ${person[name]} # John
# Loop through keys:
for key in "${!person[@]}"; do
echo "$key: ${person[$key]}"
done
Practical Script Examples
Backup script:
#!/bin/bash
# Configuration
SOURCE="/home/user/documents"
DEST="/backup"
DATE=$(date +%Y%m%d_%H%M%S)
ARCHIVE="backup_$DATE.tar.gz"
# Create backup
echo "Starting backup..."
tar -czf "$DEST/$ARCHIVE" "$SOURCE"
if [[ $? -eq 0 ]]; then
echo "Backup successful: $ARCHIVE"
else
echo "Backup failed!"
exit 1
fi
# Delete backups older than 30 days
find "$DEST" -name "backup_*.tar.gz" -mtime +30 -delete
echo "Cleanup complete"
Log analyzer:
#!/bin/bash
LOG_FILE="/var/log/apache2/access.log"
echo "=== Top 10 IP Addresses ==="
awk '{print $1}' "$LOG_FILE" | sort | uniq -c | sort -nr | head -10
echo ""
echo "=== Top 10 Requested Pages ==="
awk '{print $7}' "$LOG_FILE" | sort | uniq -c | sort -nr | head -10
echo ""
echo "=== HTTP Status Codes ==="
awk '{print $9}' "$LOG_FILE" | sort | uniq -c | sort -nr
System monitoring:
#!/bin/bash
# Check if disk usage exceeds 80%
USAGE=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
if [[ $USAGE -gt 80 ]]; then
echo "WARNING: Disk usage is ${USAGE}%"
# Send email, SMS, etc.
fi
# Check if service is running
if ! systemctl is-active --quiet nginx; then
echo "ERROR: Nginx is not running"
sudo systemctl start nginx
fi
12. Input/Output Redirection
Control where commands read input and send output.
Output Redirection
Redirect stdout:
ls -la > file_list.txt # Overwrite
ls -la >> file_list.txt # Append
Redirect stderr:
command 2> errors.log # Only errors
command 2>> errors.log # Append errors
Redirect both stdout and stderr:
command &> output.log # Both to same file
command > output.log 2>&1 # Traditional syntax
command 2>&1 | tee output.log # Both to file and screen
Discard output:
command > /dev/null # Discard stdout
command 2> /dev/null # Discard stderr
command &> /dev/null # Discard both
Understanding file descriptors:
0= stdin (standard input)1= stdout (standard output)2= stderr (standard error)
Swap stdout and stderr:
command 3>&1 1>&2 2>&3
Input Redirection
# Feed file as input:
sort < unsorted.txt
# Here document (multi-line input):
cat << EOF > output.txt
Line 1
Line 2
Line 3
EOF
# Here string:
grep "pattern" <<< "text to search"
Practical Examples
Separate output and errors:
./script.sh > output.log 2> errors.log
Log everything:
./script.sh &> full.log
Show and log:
./script.sh 2>&1 | tee output.log
Silent execution:
cron_job.sh &> /dev/null
13. Advanced Techniques and Power User Features
SSH Key-Based Authentication
Eliminate passwords and enhance security:
1. Generate key pair (on local machine):
ssh-keygen -t ed25519 -C "your_email@example.com"
Or RSA for older systems:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Press Enter to accept defaults. Optionally set a passphrase.
2. Copy public key to server:
ssh-copy-id user@server.com
Or manually:
cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
3. Test:
ssh user@server.com # No password required!
Security hardening:
Edit /etc/ssh/sshd_config on server:
PasswordAuthentication no
PermitRootLogin no
PubkeyAuthentication yes
Restart SSH:
sudo systemctl restart sshd
Terminal Multiplexers: tmux and screen
Run persistent sessions that survive disconnections.
tmux Basics
Start session:
tmux
tmux new -s session_name
Detach from session:
Press Ctrl+B, then D
List sessions:
tmux ls
Attach to session:
tmux attach
tmux attach -t session_name
Essential tmux commands (prefix with Ctrl+B):
C: Create new windowN: Next windowP: Previous window0-9: Switch to window by number%: Split pane vertically": Split pane horizontally- Arrow keys: Navigate between panes
D: Detach from sessionX: Kill current pane&: Kill current window?: Show all keybindings
Workflow example:
# SSH into server:
ssh user@server.com
# Start tmux:
tmux new -s deployment
# Run long process:
./deploy_application.sh
# Detach: Ctrl+B, then D
# Log out: exit
# Later, reconnect:
ssh user@server.com
tmux attach -t deployment
# Your process is still running!
screen Basics
Start session:
screen
screen -S session_name
Detach from session:
Press Ctrl+A, then D
List sessions:
screen -ls
Attach to session:
screen -r
screen -r session_name
Essential screen commands (prefix with Ctrl+A):
C: Create new windowN: Next windowP: Previous window0-9: Switch to window by numberS: Split horizontally|: Split vertically (requires configuration)Tab: Switch between splitsD: DetachK: Kill current window?: Help
Why use multiplexers:
- Run long processes on remote servers without keeping SSH connected
- Organize multiple terminal windows in one interface
- Share sessions with other users (pair programming)
- Recover from network interruptions
Advanced Find Techniques
Find and execute complex operations:
# Find files older than 30 days and compress them:
find /var/log -name "*.log" -mtime +30 -exec gzip {} \;
# Find large files and show them sorted:
find / -type f -size +100M -exec ls -lh {} \; | sort -k5 -h
# Find and move files:
find . -name "*.tmp" -exec mv {} /tmp/ \;
# Find with multiple conditions:
find . -type f \( -name "*.log" -o -name "*.txt" \) -size +1M
# Find and confirm before deleting:
find . -name "*.bak" -ok rm {} \;
# Find files modified today:
find . -type f -mtime 0
# Find files by permissions:
find . -type f -perm 777 # Exactly 777
find . -type f -perm -644 # At least 644
# Find empty files and directories:
find . -empty
# Find by owner:
find /home -user john
# Find and change permissions:
find . -type f -name "*.sh" -exec chmod +x {} \;
Advanced xargs patterns:
# Process in batches:
find . -name "*.jpg" -print0 | xargs -0 -n 10 -P 4 process_images.sh
# Build complex commands:
find . -name "*.log" | xargs -I {} sh -c 'echo "Processing {}"; gzip {}'
# Handle special characters safely:
find . -name "* *" -print0 | xargs -0 rename
# Parallel processing:
find . -name "*.txt" -print0 | xargs -0 -P 8 -I {} sh -c 'wc -l {} | tee -a count.log'
Process Management Deep Dive
Advanced process inspection:
# Show process tree:
pstree -p # With PIDs
pstree -u # With usernames
# Find process by name:
pgrep -f "python app.py"
# Kill by name (careful!):
pkill -f "python app.py"
# Show threads:
ps -T -p PID
# Real-time process monitoring with filtering:
watch -n 1 'ps aux | grep python'
# CPU-consuming processes:
ps aux --sort=-%cpu | head -10
# Memory-consuming processes:
ps aux --sort=-%mem | head -10
# Process with specific state:
ps aux | awk '$8 ~ /^Z/ {print}' # Zombie processes
Nice and renice (process priority):
# Start with lower priority:
nice -n 10 ./cpu_intensive_task.sh
# Change priority of running process:
renice -n 5 -p PID
# Priority levels: -20 (highest) to 19 (lowest)
# Default: 0
Process signals:
kill -l # List all signals
# Common signals:
kill -TERM PID # Graceful termination (default)
kill -KILL PID # Force kill (same as kill -9)
kill -HUP PID # Hangup (reload config)
kill -STOP PID # Pause
kill -CONT PID # Resume
kill -USR1 PID # User-defined signal 1
kill -USR2 PID # User-defined signal 2
Advanced Text Processing Patterns
Complex awk programs:
# Print lines with specific field value:
awk '$3 > 100 && $5 == "active"' data.txt
# Calculate and format:
awk '{sum += $2} END {printf "Total: $%.2f\n", sum}' prices.txt
# Field manipulation:
awk '{print $2, $1}' file.txt | column -t # Swap and align
# Multiple patterns:
awk '/ERROR/ {errors++} /WARNING/ {warnings++} END {print "Errors:", errors, "Warnings:", warnings}' log.txt
# Process CSV with headers:
awk -F',' 'NR==1 {for(i=1;i<=NF;i++) header[i]=$i} NR>1 {print header[1]": "$1, header[2]": "$2}' data.csv
Sed scripting:
# Multiple substitutions:
sed -e 's/old1/new1/g' -e 's/old2/new2/g' file.txt
# Conditional replacement:
sed '/pattern/s/old/new/g' file.txt
# Delete range of lines:
sed '10,20d' file.txt
# Insert line before pattern:
sed '/pattern/i\New line here' file.txt
# Append line after pattern:
sed '/pattern/a\New line here' file.txt
# Change entire line:
sed '/pattern/c\Replacement line' file.txt
# Multiple commands from file:
sed -f commands.sed input.txt
Combining tools for complex parsing:
# Extract URLs from HTML:
grep -oP 'href="\K[^"]+' page.html | sort -u
# Parse JSON (with jq):
curl -s https://api.example.com/data | jq '.items[] | select(.status=="active") | .name'
# Parse log timestamps:
awk '{print $4}' access.log | cut -d: -f1 | sort | uniq -c
# Extract email addresses:
grep -oE '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' file.txt
Command History Tricks
Search history:
history | grep command # Search history
Ctrl+R # Reverse search (interactive)
!! # Repeat last command
!n # Run command number n
!-n # Run nth command from end
!string # Run most recent command starting with string
!?string # Run most recent command containing string
^old^new # Replace text in last command
History expansion:
# Reuse arguments:
!$ # Last argument of previous command
!* # All arguments of previous command
!^ # First argument of previous command
# Example:
ls /var/log/nginx/
cd !$ # Changes to /var/log/nginx/
Configure history:
# Add to ~/.bashrc:
export HISTSIZE=10000 # Commands in memory
export HISTFILESIZE=20000 # Commands in file
export HISTTIMEFORMAT="%F %T " # Add timestamps
export HISTCONTROL=ignoredups # Ignore duplicates
export HISTIGNORE="ls:cd:pwd" # Ignore specific commands
# Share history across terminals:
shopt -s histappend
PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"
Bash Aliases and Functions
Create aliases (add to ~/.bashrc):
# Navigation shortcuts:
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
# Safety nets:
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
# Common commands:
alias ll='ls -lah'
alias la='ls -A'
alias l='ls -CF'
alias grep='grep --color=auto'
# Git shortcuts:
alias gs='git status'
alias ga='git add'
alias gc='git commit'
alias gp='git push'
# System info:
alias ports='netstat -tulanp'
alias meminfo='free -m -l -t'
alias psg='ps aux | grep -v grep | grep -i -e VSZ -e'
# Safety:
alias mkdir='mkdir -pv'
# Reload bash config:
alias reload='source ~/.bashrc'
Create functions (more powerful than aliases):
# Extract any archive:
extract() {
if [ -f $1 ]; then
case $1 in
*.tar.bz2) tar xjf $1 ;;
*.tar.gz) tar xzf $1 ;;
*.bz2) bunzip2 $1 ;;
*.rar) unrar x $1 ;;
*.gz) gunzip $1 ;;
*.tar) tar xf $1 ;;
*.tbz2) tar xjf $1 ;;
*.tgz) tar xzf $1 ;;
*.zip) unzip $1 ;;
*.Z) uncompress $1 ;;
*.7z) 7z x $1 ;;
*) echo "'$1' cannot be extracted" ;;
esac
else
echo "'$1' is not a valid file"
fi
}
# Create and enter directory:
mkcd() {
mkdir -p "$1" && cd "$1"
}
# Quick backup:
backup() {
cp "$1" "$1.backup-$(date +%Y%m%d-%H%M%S)"
}
# Find and replace in files:
replace() {
grep -rl "$1" . | xargs sed -i "s/$1/$2/g"
}
# Show PATH one per line:
path() {
echo "$PATH" | tr ':' '\n'
}
Performance Optimization
Benchmark commands:
# Time command execution:
time command
# More detailed:
/usr/bin/time -v command
# Benchmark alternatives:
hyperfine "command1" "command2" # Install separately
Monitor system performance:
# I/O statistics:
iostat -x 1
# Disk activity:
iotop
# Network bandwidth:
iftop
nload
# System calls:
strace -c command
# Open files by process:
lsof -p PID
# System load:
uptime
w
Disk performance:
# Test write speed:
dd if=/dev/zero of=testfile bs=1M count=1000
# Test read speed:
dd if=testfile of=/dev/null bs=1M
# Clear cache before testing:
sudo sh -c "sync; echo 3 > /proc/sys/vm/drop_caches"
# Measure disk I/O:
sudo hdparm -Tt /dev/sda
Security Best Practices
File security:
# Find files with dangerous permissions:
find / -type f -perm -002 2>/dev/null # World-writable files
find / -type f -perm -4000 2>/dev/null # SUID files
# Secure SSH directory:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub
chmod 644 ~/.ssh/authorized_keys
chmod 644 ~/.ssh/known_hosts
# Remove world permissions:
chmod o-rwx file
# Set restrictive umask:
umask 077 # New files: 600, directories: 700
Monitor security:
# Check for failed login attempts:
sudo grep "Failed password" /var/log/auth.log
# Show recent logins:
last
# Show currently logged-in users:
w
who
# Check for listening ports:
sudo netstat -tulpn
sudo ss -tulpn
# Review sudo usage:
sudo grep sudo /var/log/auth.log
Secure file deletion:
# Overwrite before deletion:
shred -vfz -n 3 sensitive_file.txt
# Wipe free space (use carefully):
# sfill -l /path/to/mount
Systemd Service Management
Control services:
# Start/stop/restart:
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx # Reload config without restart
# Enable/disable (start on boot):
sudo systemctl enable nginx
sudo systemctl disable nginx
# Check status:
sudo systemctl status nginx
sudo systemctl is-active nginx
sudo systemctl is-enabled nginx
# List all services:
systemctl list-units --type=service
systemctl list-units --type=service --state=running
# View logs:
sudo journalctl -u nginx
sudo journalctl -u nginx -f # Follow
sudo journalctl -u nginx --since "1 hour ago"
sudo journalctl -u nginx --since "2024-10-01" --until "2024-10-24"
# Failed services:
systemctl --failed
Create custom service:
# Create /etc/systemd/system/myapp.service:
[Unit]
Description=My Application
After=network.target
[Service]
Type=simple
User=myuser
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/run.sh
Restart=on-failure
RestartSec=10
[Install]
WantedBy=multi-user.target
# Enable and start:
sudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp
Cron Job Automation
Edit crontab:
crontab -e # Edit your crontab
crontab -l # List your crontab
crontab -r # Remove your crontab
sudo crontab -u username -e # Edit another user's crontab
Crontab syntax:
# ββββββββββββββ minute (0-59)
# β ββββββββββββββ hour (0-23)
# β β ββββββββββββββ day of month (1-31)
# β β β ββββββββββββββ month (1-12)
# β β β β ββββββββββββββ day of week (0-6, Sunday=0)
# β β β β β
# β β β β β
# * * * * * command to execute
Common patterns:
# Every minute:
* * * * * /path/to/script.sh
# Every 5 minutes:
*/5 * * * * /path/to/script.sh
# Every hour:
0 * * * * /path/to/script.sh
# Daily at 2:30 AM:
30 2 * * * /path/to/script.sh
# Every Sunday at midnight:
0 0 * * 0 /path/to/script.sh
# First day of month:
0 0 1 * * /path/to/script.sh
# Weekdays at 6 AM:
0 6 * * 1-5 /path/to/script.sh
# Multiple times:
0 6,12,18 * * * /path/to/script.sh
# At system reboot:
@reboot /path/to/script.sh
# Special shortcuts:
@yearly # 0 0 1 1 *
@monthly # 0 0 1 * *
@weekly # 0 0 * * 0
@daily # 0 0 * * *
@hourly # 0 * * * *
Best practices for cron:
# Use absolute paths:
0 2 * * * /usr/bin/python3 /home/user/backup.py
# Redirect output:
0 2 * * * /path/to/script.sh > /var/log/script.log 2>&1
# Set environment variables:
PATH=/usr/local/bin:/usr/bin:/bin
SHELL=/bin/bash
0 2 * * * /path/to/script.sh
# Email results (if mail configured):
MAILTO=admin@example.com
0 2 * * * /path/to/script.sh
Regular Expressions Power
Grep with regex:
# Basic patterns:
grep '^Start' file.txt # Lines starting with "Start"
grep 'end$' file.txt # Lines ending with "end"
grep '^$' file.txt # Empty lines
grep '[0-9]' file.txt # Lines with digits
grep '[A-Z]' file.txt # Lines with uppercase
grep '[aeiou]' file.txt # Lines with vowels
# Extended regex (-E):
grep -E 'cat|dog' file.txt # cat OR dog
grep -E 'colou?r' file.txt # color or colour
grep -E '[0-9]+' file.txt # One or more digits
grep -E '[0-9]{3}' file.txt # Exactly 3 digits
grep -E '[0-9]{2,4}' file.txt # 2 to 4 digits
# Perl regex (-P):
grep -P '\d+' file.txt # Digits (\d)
grep -P '\w+' file.txt # Word characters (\w)
grep -P '\s+' file.txt # Whitespace (\s)
grep -P '(?=.*\d)(?=.*[a-z])' # Lookahead assertions
# Email addresses:
grep -E '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' file.txt
# IP addresses:
grep -E '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' file.txt
# URLs:
grep -E 'https?://[^\s]+' file.txt
Command Line Efficiency Tips
Keyboard shortcuts:
Ctrl+A # Move to beginning of line
Ctrl+E # Move to end of line
Ctrl+U # Delete from cursor to beginning
Ctrl+K # Delete from cursor to end
Ctrl+W # Delete word before cursor
Alt+D # Delete word after cursor
Ctrl+L # Clear screen (like 'clear')
Ctrl+R # Reverse search history
Ctrl+G # Escape from reverse search
Ctrl+C # Cancel current command
Ctrl+Z # Suspend current command
Ctrl+D # Exit shell (or send EOF)
!! # Repeat last command
sudo !! # Repeat last command with sudo
Quick edits:
# Fix typo in previous command:
^typo^correction
# Example:
$ grpe error log.txt
^grpe^grep
# Runs: grep error log.txt
Brace expansion:
# Create multiple files:
touch file{1..10}.txt
# Creates: file1.txt, file2.txt, ..., file10.txt
# Create directory structure:
mkdir -p project/{src,bin,lib,doc}
# Copy with backup:
cp file.txt{,.bak}
# Same as: cp file.txt file.txt.bak
# Multiple extensions:
rm file.{txt,log,bak}
Command substitution:
# Use command output in another command:
echo "Today is $(date)"
mv file.txt file.$(date +%Y%m%d).txt
# Nested:
echo "Files: $(ls $(pwd))"
14. Troubleshooting and Debugging
Common Problems and Solutions
βCommand not foundβ:
# Check if command exists:
which command_name
type command_name
# Check PATH:
echo $PATH
# Find where command is:
find / -name command_name 2>/dev/null
# Add to PATH temporarily:
export PATH=$PATH:/new/directory
# Add to PATH permanently (add to ~/.bashrc):
export PATH=$PATH:/new/directory
βPermission deniedβ:
# Check permissions:
ls -l file
# Make executable:
chmod +x script.sh
# Check ownership:
ls -l file
# Change ownership:
sudo chown user:group file
# Run with sudo:
sudo command
βNo space left on deviceβ:
# Check disk space:
df -h
# Find large directories:
du -sh /* | sort -h
# Find large files:
find / -type f -size +100M -exec ls -lh {} \;
# Clear package cache (Ubuntu/Debian):
sudo apt clean
# Clear systemd journal:
sudo journalctl --vacuum-time=7d
βToo many open filesβ:
# Check current limit:
ulimit -n
# Increase limit (temporary):
ulimit -n 4096
# Check what's using files:
lsof | wc -l
lsof -u username
# Permanent fix (edit /etc/security/limits.conf):
* soft nofile 4096
* hard nofile 8192
Process wonβt die:
# Try graceful kill:
kill PID
# Wait a bit, then force:
kill -9 PID
# If still alive, check:
ps aux | grep PID
# May be zombie (can't be killed, wait for parent):
ps aux | awk '$8 ~ /^Z/'
Debugging Scripts
Enable debugging:
#!/bin/bash -x # Print each command before executing
# Or:
set -x # Turn on debugging
# ... commands ...
set +x # Turn off debugging
# Strict mode (recommended):
set -euo pipefail
# -e: Exit on error
# -u: Exit on undefined variable
# -o pipefail: Pipeline fails if any command fails
Debug output:
# Add debug messages:
echo "DEBUG: variable value is $var" >&2
# Function for debug messages:
debug() {
if [[ "${DEBUG:-0}" == "1" ]]; then
echo "DEBUG: $*" >&2
fi
}
# Usage:
DEBUG=1 ./script.sh
Check syntax without running:
bash -n script.sh # Check for syntax errors
Conclusion
You now have a comprehensive guide to the Linux command line and Bash scripting, covering everything from basic navigation to advanced automation. The key to mastery is practice:
- Start simple: Use basic commands daily until they become second nature
- Build gradually: Add more complex techniques as you encounter real problems
- Automate repetitively: Turn repetitive tasks into scripts
- Read documentation: Use
manpages and--helpextensively - Experiment safely: Use test environments or directories for practice
Remember: the command line is a skill that compounds over time. Every technique you learn builds upon the last, and soon youβll find yourself crafting elegant one-liners that would have seemed impossible when you started.
Continue learning:
- Explore your systemβs man pages
- Read other usersβ scripts on GitHub
- Join Linux communities and forums
- Challenge yourself with command-line puzzles
- Build your own tools and utilities
The command line isnβt just a toolβitβs a superpower that makes you more productive, efficient, and capable. Master it, and youβll wonder how you ever worked without it.
NFS_Server
we need to setup into two part
- client side configuration
- server side configuration
Server Side Configuration: -
- To install nfs package
sudo apt install nfs-utils libnfsidmap - Enable and start nfs service
sudo systemctl enable rpcbind, nfs-serversudo systemctl start rpcbind, nfs-server, rpc-statd, nfs-idmap - Create a directory for nfs and give all the permission
mkdir -p $HOME/Desktop/NFS-Sharesudo chmod 777 ~/Desktop/NFS-Share - Modify the /etc/exports file and add new shared filesystem
/location <IP_allow>(rw,sync,no_root_squash)exportfs -rv
Client Side Configuration:-
- To install nfs package
sudo apt install nfs-utils rpcbind - Enable and start the rpcbind service
sudo systemctl start rpcbind - To stop the firewall
sudo systemctl stop firewall / iptable - show mount from nfs server
showmount -e <IP of server side> - Create a mount point (directory)
mkdir -p /mnt/share - Mount the NFS file system
mount <IP_server>:/location /mnt/share
Setting Up SSH Server Between PC and Server
This guide explains how to set up and configure an SSH server to enable secure communication between a client PC and a server.
Prerequisites
- A Linux-based PC (client) and server.
- SSH package installed on both machines.
- Network connectivity between the PC and the server.
Step-by-Step Instructions
Step 1: Install OpenSSH
On both the client and server, install the OpenSSH package:
On the Server:
sudo apt update
sudo apt install openssh-server
On the Client:
sudo apt update
sudo apt install openssh-client
Step 2: Start and Enable SSH Service
Ensure the SSH service is running on the server:
sudo systemctl start ssh
sudo systemctl enable ssh
Check the service status:
sudo systemctl status ssh
Step 3: Configure SSH on the Server
-
Open the SSH configuration file:
sudo nano /etc/ssh/sshd_config -
Modify or verify the following settings:
- PermitRootLogin: Set to
nofor security. - PasswordAuthentication: Set to
yesto allow password-based logins initially (you can disable it after setting up key-based authentication).
- PermitRootLogin: Set to
-
Save changes and restart the SSH service:
sudo systemctl restart ssh
Step 4: Determine the Serverβs IP Address
Find the serverβs IP address to connect from the client:
ip a
Look for the IP address under the active network interface (e.g., 192.168.x.x).
Step 5: Test SSH Connection from the Client
On the client, open a terminal and connect to the server using:
ssh username@server_ip
Replace username with the serverβs username and server_ip with the actual IP address.
Example:
ssh user@192.168.1.10
**Step 6: Set Up Key-Based Authentication
-
On the client, generate an SSH key pair:
ssh-keygen -t rsa -b 4096 -
Copy the public key to the server: on Linux
ssh-copy-id username@server_ipon Windows go to the .ssh folder
scp $env:USERPROFILE/.ssh/id_rsa.pub username@ip:~/.ssh/authorized_keys
-
Verify key-based login:
ssh username@server_ip -
Disable password-based logins for added security:
-
Edit the serverβs SSH configuration file:
sudo nano /etc/ssh/sshd_config -
Set
PasswordAuthenticationtono. -
Restart the SSH service:
sudo systemctl restart ssh
-
Step 7: Troubleshooting Common Issues
-
Firewall: Ensure SSH traffic is allowed through the firewall on the server:
sudo ufw allow ssh sudo ufw enable -
Connection Refused: Check if the SSH service is running and the correct IP address is used.
PostfixMail
Postfix Config lines
Add the following lines to /etc/postfix/main.cf
relayhost = [smtp.gmail.com]:587 myhostname= your_hostname
Location of sasl_passwd we saved smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd
Enables SASL authentication for postfix smtp_sasl_auth_enable = yes smtp_tls_security_level = encrypt
Disallow methods that allow anonymous authentication smtp_sasl_security_options = noanonymous
Create a file under /etc/postfix/sasl/
Filename: sasl_passwd
Add the below line [smtp.gmail.com]:587 email@gmail.com:password
change directory to cd /etc/postfix/sasl
change the ownership sudo chown root:root *
change the permission sudo chmod 600 *
Convert the sasl_passwd file into db file
postmap /etc/postfix/sasl/sasl_passwd
Start the postfix service
To send an email using Linux terminal
echo βTest Mailβ | mail -s βPostfix TESTβ paul@gmail.com
Linux Command for System Administrator
Basic command for system monitoring
sudo du -a / | sort -n -r | head -n 20# list disk usagejournalctl | grep "error"# log messages, kernel messages, and other system-related informationdmesg --ctime | grep error# Show kernel ring buffersudo journalctl -p 3 -xb# Check the lock filesudo systemctl --failed# Service that failed to loaddu -sh .config# File size of a specific directoryfind . -type f -exec grep -l "/dev/nvme0n1" {} +# find file and exce command with grep, {} is the output for each & +,\; is the terminator
Reset password (for forgotten password)
Reser Root
init=/bin/bash# from grub commnad mode, find the kernel line containing linux then add at the end of linux commandctrl+xorF10# to save the changes and bootmount -o remount,rw /# mount the root system for (r,w)passwd# change the passwordreboot -f# force reboot, after that you can boot with new passwd you set
Reser User
rw init=/bin/bash# from grub commnad mode, find the kernel line containing linux then add at the end of linux commandctrl+xorF10# to save the changes and bootpasswd username# change the passwordreboot -f# force reboot, after that you can boot with new passwd you set
Some useful Command
grep -Irl "akib" .# this will find file contain akib in the current dirgrep -A 3 -B 3 "nvme" flake.nix# this will find nvme in flake.nix file with before and after with 3,3 linesed -i "s/akib/withNewText/g" file.txt# sed will changes the all occurance with new text in a filecat /etc/passwd | column -t -s ":" -N USERNAME,PW,UID,GUID,COMMENT,HOME,INTERPRETER -J -n passwdFile# will seperate passwd file based on β:β delemeter and show as column format then the β-Jβ flag will convert it into json filecat /etc/passwd | awk -F: 'BEGIN {printf "user\tPW\tUID\tGUID\tCOMMENT\tHOME\tINTERPRETER\n"} {printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\n", $1, $2, $3, $4, $5, $6, $7}'cat /etc/passwd | column -t -s ":" -N USERNAME,PW,UID,GUID,COMMENT,HOME,INTERPRETER -H PW -O UID,USERNAME,GUID,COMMENT,HOME,INTERPRETER# β-Hβ remove specific column β-Oβ reorder column
Basic
π οΈ Common Ports & Protocols Cheat Sheet
A quick reference for well-known TCP/UDP ports and their usage. Useful for students, professionals, and anyone studying for certifications like CCNA, CompTIA, or Security+.
π Well-Known / System Ports (0 β 1023)
| Port | Service | Protocol | Description |
|---|---|---|---|
| 7 | Echo | TCP, UDP | Echo service |
| 19 | CHARGEN | TCP, UDP | Character Generator Protocol (rarely used, vulnerable) |
| 20 | FTP-data | TCP, SCTP | File Transfer Protocol (data) |
| 21 | FTP | TCP, UDP, SCTP | File Transfer Protocol (control) |
| 22 | SSH/SCP/SFTP | TCP, UDP, SCTP | Secure Shell, secure logins, file transfers, port forwarding |
| 23 | Telnet | TCP | Unencrypted text communication |
| 25 | SMTP | TCP | Simple Mail Transfer Protocol (email routing) |
| 53 | DNS | TCP, UDP | Domain Name System |
| 67 | DHCP/BOOTP | UDP | DHCP Server |
| 68 | DHCP/BOOTP | UDP | DHCP Client |
| 69 | TFTP | UDP | Trivial File Transfer Protocol |
| 80 | HTTP | TCP, UDP, SCTP | Web traffic (HTTP/1.x, HTTP/2 over TCP; HTTP/3 uses QUIC/UDP) |
| 88 | Kerberos | TCP, UDP | Network authentication system |
| 110 | POP3 | TCP | Post Office Protocol (email retrieval) |
| 123 | NTP | UDP | Network Time Protocol |
| 135 | Microsoft RPC EPMAP | TCP, UDP | Remote Procedure Call Endpoint Mapper |
| 137-139 | NetBIOS | TCP, UDP | NetBIOS services (name service, datagram, session) |
| 143 | IMAP | TCP, UDP | Internet Message Access Protocol |
| 161-162 | SNMP | UDP | Simple Network Management Protocol (unencrypted) |
| 179 | BGP | TCP | Border Gateway Protocol |
| 389 | LDAP | TCP, UDP | Lightweight Directory Access Protocol |
| 443 | HTTPS | TCP, UDP, SCTP | Secure web traffic (SSL/TLS) |
| 445 | Microsoft DS SMB | TCP, UDP | File sharing, Active Directory |
| 465 | SMTPS | TCP | SMTP over SSL/TLS |
| 514 | Syslog | UDP | System log protocol |
| 520 | RIP | UDP | Routing Information Protocol |
| 546-547 | DHCPv6 | UDP | DHCP for IPv6 (client/server) |
| 636 | LDAPS | TCP, UDP | LDAP over SSL |
| 993 | IMAPS | TCP | IMAP over SSL/TLS |
| 995 | POP3S | TCP, UDP | POP3 over SSL/TLS |
π Registered Ports (1024 β 49151)
| Port | Service | Protocol | Description |
|---|---|---|---|
| 1025 | Microsoft RPC | TCP | RPC service |
| 1080 | SOCKS proxy | TCP, UDP | Proxy protocol |
| 1194 | OpenVPN | TCP, UDP | VPN tunneling |
| 1433 | MS-SQL Server | TCP | Microsoft SQL Server |
| 1521 | Oracle DB | TCP | Oracle Database listener |
| 1701 | L2TP | TCP | Layer 2 Tunneling Protocol |
| 1720 | H.323 | TCP | VoIP signaling |
| 1723 | PPTP | TCP, UDP | VPN protocol (deprecated) |
| 1812-1813 | RADIUS | UDP | Authentication, accounting |
| 2049 | NFS | UDP | Network File System |
| 2082-2083 | cPanel | TCP, UDP | Web hosting control panel |
| 2222 | DirectAdmin | TCP | Hosting control panel |
| 2483-2484 | Oracle DB | TCP, UDP | Insecure & SSL listener |
| 3074 | Xbox Live | TCP, UDP | Online gaming |
| 3128 | HTTP Proxy | TCP | Common proxy port |
| 3260 | iSCSI Target | TCP, UDP | Storage protocol |
| 3306 | MySQL | TCP | Database system |
| 3389 | RDP | TCP | Windows Remote Desktop |
| 3690 | SVN | TCP, UDP | Apache Subversion |
| 3724 | World of Warcraft | TCP, UDP | Gaming |
| 4333 | mSQL | TCP | Mini SQL |
| 4444 | Blaster Worm | TCP, UDP | Malware |
| 5000 | UPnP | TCP | Universal Plug & Play |
| 5060-5061 | SIP | TCP, UDP | Session Initiation Protocol (VoIP) |
| 5222-5223 | XMPP | TCP, UDP | Messaging protocol |
| 5432 | PostgreSQL | TCP | Database system |
| 5900-5999 | VNC | TCP, UDP | Remote desktop (VNC) |
| 6379 | Redis | TCP | In-memory database |
| 6665-6669 | IRC | TCP | Internet Relay Chat |
| 6881-6999 | BitTorrent | TCP, UDP | File sharing |
| 8080 | HTTP Proxy/Alt | TCP | Alternate web port |
| 8443 | HTTPS Alt | TCP | Alternate secure web port |
| 9042 | Cassandra | TCP | NoSQL database |
| 9100 | Printer (PDL) | TCP | Print Data Stream |
π Dynamic / Private Ports (49152 β 65535)
These are used for ephemeral connections and custom apps. Safe to use for internal development/testing.
π― Most Common Ports for Exams
If youβre preparing for CCNA / CompTIA exams, focus on these:
| Port | Service |
|---|---|
| 7 | Echo |
| 20, 21 | FTP |
| 22 | SSH/SCP |
| 23 | Telnet |
| 25 | SMTP |
| 53 | DNS |
| 67, 68 | DHCP |
| 69 | TFTP |
| 80 | HTTP |
| 88 | Kerberos |
| 110 | POP3 |
| 123 | NTP |
| 137-139 | NetBIOS |
| 143 | IMAP |
| 161, 162 | SNMP |
| 389 | LDAP |
| 443 | HTTPS |
| 445 | SMB |
| 636 | LDAPS |
| 3389 | RDP |
| 5060-5061 | SIP (VoIP) |
β Conclusion
Familiarity with ports & protocols is essential for:
- Building secure applications
- Troubleshooting network issues
- Passing certification exams
Keep this cheat sheet handy as a quick reference!
IPv4 Subnetting Cheat Sheet
Subnetting is one of the most fundamental yet challenging concepts in networking. This cheat sheet provides quick references to help you master IPv4 subnetting for certifications, administration, and network design.
IPv4 Subnets
Subnetting allows a host to determine if the destination machine is local or remote. The subnet mask determines how many IPv4 addresses are assignable within a network.
| CIDR | Subnet Mask | # of Addresses | Wildcard |
|---|---|---|---|
| /32 | 255.255.255.255 | 1 | 0.0.0.0 |
| /31 | 255.255.255.254 | 2 | 0.0.0.1 |
| /30 | 255.255.255.252 | 4 | 0.0.0.3 |
| /29 | 255.255.255.248 | 8 | 0.0.0.7 |
| /28 | 255.255.255.240 | 16 | 0.0.0.15 |
| /27 | 255.255.255.224 | 32 | 0.0.0.31 |
| /26 | 255.255.255.192 | 64 | 0.0.0.63 |
| /25 | 255.255.255.128 | 128 | 0.0.0.127 |
| /24 | 255.255.255.0 | 256 | 0.0.0.255 |
| /23 | 255.255.254.0 | 512 | 0.0.1.255 |
| /22 | 255.255.252.0 | 1024 | 0.0.3.255 |
| /21 | 255.255.248.0 | 2,048 | 0.0.7.255 |
| /20 | 255.255.240.0 | 4,096 | 0.0.15.255 |
| /19 | 255.255.224.0 | 8,192 | 0.0.31.255 |
| /18 | 255.255.192.0 | 16,384 | 0.0.63.255 |
| /17 | 255.255.128.0 | 32,768 | 0.0.127.255 |
| /16 | 255.255.0.0 | 65,536 | 0.0.255.255 |
| /15 | 255.254.0.0 | 131,072 | 0.1.255.255 |
| /14 | 255.252.0.0 | 262,144 | 0.3.255.255 |
| /13 | 255.248.0.0 | 524,288 | 0.7.255.255 |
| /12 | 255.240.0.0 | 1,048,576 | 0.15.255.255 |
| /11 | 255.224.0.0 | 2,097,152 | 0.31.255.255 |
| /10 | 255.192.0.0 | 4,194,304 | 0.63.255.255 |
| /9 | 255.128.0.0 | 8,388,608 | 0.127.255.255 |
| /8 | 255.0.0.0 | 16,777,216 | 0.255.255.255 |
| /7 | 254.0.0.0 | 33,554,432 | 1.255.255.255 |
| /6 | 252.0.0.0 | 67,108,864 | 3.255.255.255 |
| /5 | 248.0.0.0 | 134,217,728 | 7.255.255.255 |
| /4 | 240.0.0.0 | 268,435,456 | 15.255.255.255 |
| /3 | 224.0.0.0 | 536,870,912 | 31.255.255.255 |
| /2 | 192.0.0.0 | 1,073,741,824 | 63.255.255.255 |
| /1 | 128.0.0.0 | 2,147,483,648 | 127.255.255.255 |
| /0 | 0.0.0.0 | 4,294,967,296 | 255.255.255.255 |
Decimal to Binary Conversion
IPv4 addresses are actually 32-bit binary numbers. Subnet masks in binary show which part is the network and which part is the host.
| Subnet Mask | Binary | Wildcard | Binary Wildcard |
|---|---|---|---|
| 255 | 1111 1111 | 0 | 0000 0000 |
| 254 | 1111 1110 | 1 | 0000 0001 |
| 252 | 1111 1100 | 3 | 0000 0011 |
| 248 | 1111 1000 | 7 | 0000 0111 |
| 240 | 1111 0000 | 15 | 0000 1111 |
| 224 | 1110 0000 | 31 | 0001 1111 |
| 192 | 1100 0000 | 63 | 0011 1111 |
| 128 | 1000 0000 | 127 | 0111 1111 |
| 0 | 0000 0000 | 255 | 1111 1111 |
Why Learn Binary?
1= Network portion0= Host portion- Subnet masks must have all ones followed by all zeros.
Example: A /24 (255.255.255.0) subnet reserves 24 bits for network and 8 bits for hosts β 254 usable IPs.
/28 Example: If ISP gives 199.44.6.80/28, you calculate host addresses by binary increments β usable range = .81 - .94.
IPv4 Address Classes
| Class | Range |
|---|---|
| A | 0.0.0.0 β 127.255.255.255 |
| B | 128.0.0.0 β 191.255.255.255 |
| C | 192.0.0.0 β 223.255.255.255 |
| D | 224.0.0.0 β 239.255.255.255 |
| E | 240.0.0.0 β 255.255.255.255 |
Reserved (Private) Ranges
| Range Type | IP Range |
|---|---|
| Class A | 10.0.0.0 β 10.255.255.255 |
| Class B | 172.16.0.0 β 172.31.255.255 |
| Class C | 192.168.0.0 β 192.168.255.255 |
| Localhost | 127.0.0.0 β 127.255.255.255 |
| Zeroconf (APIPA) | 169.254.0.0 β 169.254.255.255 |
Key Terminology
- Wildcard Mask: Indicates available address bits for matching.
- CIDR: Classless Inter-Domain Routing, uses
/XXnotation. - Network Portion: Fixed part of IP determined by subnet mask.
- Host Portion: Variable part of IP usable for devices.
Conclusion
IPv4 subnetting can seem complex, but with practice and binary understanding, it becomes second nature. Keep this sheet handy for quick reference during exams, troubleshooting, or design work.
Tools
curl Cheat Sheet
Quick: Practical, consultant-style reference for using
curlβ from basic GETs to file uploads, API interactions, cookies, scripting tips and advanced flags. Friendly tone, focused on getting you productive fast.
Table of contents
- What is curl?
- Quick examples β Web browsing & headers
- Downloading files
- GET requests
- POST requests & forms
- API interaction & headers
- File uploads with
--form/-F - Cookies and sessions
- Scripting with curl
- Advanced & debugging flags
- Partial downloads & ranges
- Helpful one-line examples
- Etiquette & safety note
What is curl?
curl (client URL) is a command-line tool for transferring data with URL syntax. It supports many protocols (HTTP/S, FTP, SCP, SMTP, IMAP, POP3, etc.) and is ideal for quick checks, automation, scripting, API calls, and sometimes creative (or mischievous) automation.
Use it when you need protocol-level control from the terminal.
Quick examples β Web browsing & headers
| Command | Description |
|---|---|
curl http://example.com | Print HTML body of http://example.com to stdout |
curl --list-only "http://example.com/dir/" (-l) | List directory contents (if server allows) |
curl --location URL (-L) | Follow 3xx redirects |
curl --head URL (-I) | Fetch HTTP response headers only |
curl --head --show-error URL | Headers and errors (helpful for down/unresponsive hosts) |
Downloading files
| Command | Notes |
|---|---|
curl --output hello.html http://example.com (-o) | Save output to hello.html |
curl --remote-name URL (-O) | Save file using remote filename |
curl --remote-name URL --output newname | Download then rename locally |
curl --remote-name --continue-at - URL | Resume partial download (if server supports ranges) |
curl "https://site/{a,b,c}.html" --output "file_#1.html" | Download multiple variants using brace expansion and # placeholders |
Batch download pattern (extract links then download):
curl -L http://example.com/list/ | grep '\.mp4' | cut -d '"' -f 8 | while read i; do curl http://example.com/${i} -O; done
(Adjust grep/cut to the page structure.)
GET requests
| Command | Description |
|---|---|
curl --request GET "http://example.com" (-X GET) | Explicit GET request (usually optional) |
curl -s -w '%{remote_ip} %{time_total} %{http_code}\n' -o /dev/null URL | Silent mode with custom output: IP, total time, HTTP code |
Example: fetch a JSON API (may require headers or tokens):
curl -X GET 'https://api.example.com/items?filter=all' -H 'Accept: application/json'
POST requests & forms
| Command | Description |
|---|---|
curl --request POST URL -d 'key=value' (-X POST -d) | Send URL-encoded data in the request body |
curl -H 'Content-Type: application/json' --data-raw '{"k":"v"}' URL | Send raw JSON payload (set content-type) |
Examples with MongoDB Data API (illustrative):
# Insert document
curl --request POST 'https://data.mongodb-api/.../insertOne' \
--header 'Content-Type: application/json' \
--header 'api-key: YOUR_KEY' \
--data-raw '{"dataSource":"Cluster0","database":"db","collection":"c","document":{ "name":"Alice" }}'
# Find one
curl --request POST 'https://data.mongodb-api/.../findOne' \
--header 'Content-Type: application/json' \
--header 'api-key: YOUR_KEY' \
--data-raw '{"filter":{"name":"Alice"}}'
API interaction & headers
| Command | Description |
|---|---|
-H / --header | Add custom HTTP header (Auth tokens, Content-Type, Accept, etc.) |
curl --header "Auth-Token:$TOKEN" URL | Pass bearer or custom tokens in headers |
curl --user username:password URL | Basic auth (-u username:password) |
Examples:
curl -H 'Authorization: Bearer $TOKEN' -H 'Accept: application/json' https://api.example.com/me
curl -u 'user:password' 'https://example.com/protected'
File uploads with --form / -F
Use -F to emulate HTML form file uploads (multipart/form-data).
| Command | Description |
|---|---|
curl --form "file=@/path/to/file" URL | Upload file (use @ for relative or @/abs/path) |
curl --form "field=value" --form "file=@/path" URL | Mix fields and files in one request |
Notes:
- If the file is in the current directory, you can use
@filename. - If you supply an absolute path, omit the
@and passfield=/full/path.
Examples:
curl -F "email=test@me.com" -F "submit=Submit" 'https://docs.google.com/forms/d/e/FORM_ID/formResponse' > output.html
curl -F "entry.123456789=@/Users/me/pic.jpg" 'https://example.com/upload' > response.html
Cookies and sessions
| Command | Description |
|---|---|
curl --cookie "name=val;name2=val2" URL (-b) | Send cookie(s) inline |
curl --cookie cookies.txt URL | Load cookies from file (cookies.txt with k=v;... format) |
curl --cookie-jar mycookies.txt URL (-c) | Save cookies received into mycookies.txt |
curl --dump-header headers.txt URL (-D) | Dump response headers (includes Set-Cookie) |
Cookie file format (simple):
key1=value1;key2=value2
Scripting with curl
curl is a natural fit for bash automation. Example script patterns:
- Reusable function wrapper for API calls (add auth header once)
- Download + checksum verification loop
- Rate-limited loops for polite scraping (
sleepbetween requests)
Example: simple reusable function
api_get(){
local endpoint="$1"
curl -s -H "Authorization: Bearer $API_KEY" "https://api.example.com/${endpoint}"
}
api_get "items"
Advanced & debugging flags
| Flag | Purpose |
|---|---|
-h | Show help |
--version | Show curl version and features |
-v | Verbose (request/response) |
--trace filename | Detailed trace of operations and data |
-s | Silent mode (no progress meter) |
-S | Show error when used with -s |
-L | Follow redirects |
--connect-timeout | Seconds to wait for TCP connect |
-m / --max-time | Max operation time in seconds |
-w / --write-out | Print variables after completion (%{http_code}, %{time_total}, %{remote_ip}, etc.) |
Examples:
curl -v https://example.com
curl --trace trace.txt https://twitter.com/
curl -s -w '%{remote_ip} %{time_total} %{http_code}\n' -o /dev/null http://ankush.io
curl -L 'https://short.url' --connect-timeout 0.1
Partial downloads & ranges
Use -r to request byte ranges from HTTP/FTP responses (helpful for resuming or grabbing file snippets).
| Command | Notes |
|---|---|
curl -r 0-99 http://example.com | First 100 bytes |
curl -r -500 http://example.com | Last 500 bytes |
curl -r 0-99 ftp://ftp.example.com | Ranges on FTP (explicit start/end required) |
Helpful one-line examples
# Show headers only
curl -I https://example.com
# Save response to file quietly
curl -sL https://example.com -o page.html
# POST JSON and pretty-print reply (using jq)
curl -s -H "Content-Type: application/json" -d '{"name":"A"}' https://api.example.com/insert | jq
# Upload file with field name "file"
curl -F "file=@./image.jpg" https://api.example.com/upload
# Send cookies from file and save response headers
curl -b cookies.txt -D headers.txt https://example.com
# Send URL-encoded form field
curl -d "field1=value1&field2=value2" -X POST https://form-endpoint
Request example (SMS via textbelt β use responsibly)
curl -X POST https://textbelt.com/text \
--data-urlencode phone='+[E.164 number]' \
--data-urlencode message='Please delete this message.' \
-d key=textbelt
Response example: {"success":true,...} (service-dependent)
Etiquette & safety note
- Only target servers or forms you own or have explicit permission to test. Abuse (flooding, unauthorized automation, fraud) is illegal and unethical.
- Prefer
--connect-timeoutand rate-limiting in scripts to avoid hammering servers. - Keep secrets out of command history β use environment variables or
--netrcwhere appropriate.
Nmap Cheat Sheet
Quick: A concise, practical reference for common Nmap workflows β target selection, scan types, discovery, NSE usage, output handling, evasion tricks, and useful one-liners. Designed like a consultantβs quick-reference: organized by category so you can scan and apply fast.
Table of contents
- Overview & Usage Tips
- Target Specification
- Scan Techniques
- Host Discovery
- Port Specification
- Service & Version Detection
- OS Detection
- Timing & Performance
- Timing Tunables
- NSE (Nmap Scripting Engine)
- Useful NSE Examples
- Firewall / IDS Evasion & Spoofing
- Output Formats & Options
- Helpful Output Examples & Pipelines
- Miscellaneous Flags & Other Commands
- Practical Tips & Etiquette
Overview & Usage Tips
- Run Nmap as root (or with sudo) for the most feature-complete scans (e.g., SYN
-sS, raw packets, OS detection). - Start with discovery (
-sn) and light scans (-T3 -F -sV) to find live hosts before aggressive options. - Log results (
-oA) so you can re-analyze and resume scans later. - Respect scope & permissions β scanning networks you donβt own can be illegal.
Target Specification
Define which IPs/ranges/subnets Nmap should scan.
| Switch / Syntax | Example | Description |
|---|---|---|
| Single IP | nmap 192.168.1.1 | Scan a single host |
| Multiple IPs | nmap 192.168.1.1 192.168.2.1 | Scan specific hosts |
| Range | nmap 192.168.1.1-254 | Scan an IP range |
| Domain | nmap scanme.nmap.org | Scan a hostname |
| CIDR | nmap 192.168.1.0/24 | CIDR subnet scan |
-iL | nmap -iL targets.txt | Read targets from file |
-iR | nmap -iR 100 | Scan 100 random hosts |
--exclude | nmap --exclude 192.168.1.1 | Exclude host(s) from scan |
Nmap Scan Techniques
Pick based on stealth, permissions, and speed.
| Switch | Example | Description |
|---|---|---|
-sS | nmap 192.168.1.1 -sS | TCP SYN scan (stealthy; default with privileges) |
-sT | nmap 192.168.1.1 -sT | TCP connect() scan (no raw socket required) |
-sU | nmap 192.168.1.1 -sU | UDP scan |
-sA | nmap 192.168.1.1 -sA | ACK scan (firewall mapping) |
-sW | nmap 192.168.1.1 -sW | Window scan |
-sM | nmap 192.168.1.1 -sM | Maimon scan |
-A | nmap 192.168.1.1 -A | Aggressive β OS, version, scripts, traceroute |
Host Discovery
Find out which hosts are up before scanning ports or when skipping port scans.
| Switch | Example | Description |
|---|---|---|
-sL | nmap 192.168.1.1-3 -sL | List scan β do not send probes (target listing only) |
-sn | nmap 192.168.1.1/24 -sn | Ping / host discovery only (no port scan) |
-Pn | nmap 192.168.1.1-5 -Pn | Skip host discovery (treat all hosts as up) |
-PS | nmap 192.168.1.1-5 -PS22-25,80 | TCP SYN discovery on specified ports (80 default) |
-PA | nmap 192.168.1.1-5 -PA22-25,80 | TCP ACK discovery on specified ports (80 default) |
-PU | nmap 192.168.1.1-5 -PU53 | UDP discovery on specified ports (40125 default) |
-PR | nmap 192.168.1.0/24 -PR | ARP discovery (local nets only) |
-n | nmap 192.168.1.1 -n | Never perform DNS resolution |
Port Specification
Target specific ports, ranges, or mixed TCP/UDP sets.
| Switch | Example | Description |
|---|---|---|
-p | nmap 192.168.1.1 -p 21 | Scan single port |
-p | nmap 192.168.1.1 -p 21-100 | Scan port range |
-p | nmap 192.168.1.1 -p U:53,T:21-25,80 | Mix UDP and TCP ports |
-p- | nmap 192.168.1.1 -p- | Scan all TCP ports (1β65535) |
| Service names | nmap 192.168.1.1 -p http,https | Use service names instead of numbers |
-F | nmap 192.168.1.1 -F | Fast scan β top 100 ports |
--top-ports | nmap 192.168.1.1 --top-ports 2000 | Scan top N ports by frequency |
-p0- / -p-65535 | nmap 192.168.1.1 -p0- | Open-ended ranges; -p0- will scan from 0 to 65535 |
Service & Version Detection
Try to identify the service and its version running on discovered ports.
| Switch | Example | Description |
|---|---|---|
-sV | nmap 192.168.1.1 -sV | Service/version detection |
-sV --version-intensity | nmap 192.168.1.1 -sV --version-intensity 8 | Intensity 0β9. Higher = more probing |
--version-light | nmap 192.168.1.1 -sV --version-light | Lighter/faster detection (less reliable) |
--version-all | nmap 192.168.1.1 -sV --version-all | Full (intensity 9) detection |
-A | nmap 192.168.1.1 -A | Includes -sV, OS detection, NSE scripts, traceroute |
OS Detection
Fingerprint the target TCP/IP stack to guess the OS.
| Switch | Example | Description |
|---|---|---|
-O | nmap 192.168.1.1 -O | Remote OS detection (TCP/IP fingerprinting) |
--osscan-limit | nmap 192.168.1.1 -O --osscan-limit | Skip OS detection unless ports show open/closed pattern |
--osscan-guess | nmap 192.168.1.1 -O --osscan-guess | Be more aggressive about guesses |
--max-os-tries | nmap 192.168.1.1 -O --max-os-tries 1 | Limit how many OS probe attempts are made |
-A | nmap 192.168.1.1 -A | OS detection included with -A |
Timing & Performance
Built-in timing templates trade off speed vs stealth.
| Switch | Example | Description |
|---|---|---|
-T0 | nmap 192.168.1.1 -T0 | Paranoid β max IDS evasion (very slow) |
-T1 | nmap 192.168.1.1 -T1 | Sneaky β IDS evasion |
-T2 | nmap 192.168.1.1 -T2 | Polite β reduce bandwidth/CPU usage |
-T3 | nmap 192.168.1.1 -T3 | Normal (default) |
-T4 | nmap 192.168.1.1 -T4 | Aggressive β faster but noisier |
-T5 | nmap 192.168.1.1 -T5 | Insane β assumes very fast, reliable network |
Timing Tunables (Fine Control)
Adjust timeouts, parallelism, rates and retries.
--host-timeout <time>β give up on a host after this time (e.g.,--host-timeout 2m).--min-rtt-timeout,--max-rtt-timeout,--initial-rtt-timeout <time>β control probe RTT timeouts.--min-hostgroup,--max-hostgroup <size>β group size for parallel host scanning.--min-parallelism,--max-parallelism <num>β probe parallelization controls.--max-retries <tries>β maximum retransmissions.--min-rate <n>/--max-rate <n>β packet send rate bounds.
Examples:
nmap --host-timeout 4m --max-retries 2 192.168.1.1
nmap --min-rate 100 --max-rate 1000 -p- 192.168.1.0/24
NSE (Nmap Scripting Engine)
Use scripts to automate checks, fingerprinting, vulnerability discovery and enumeration.
| Switch | Example | Notes |
|---|---|---|
-sC | nmap 192.168.1.1 -sC | Run default safe scripts (convenient discovery) |
--script | nmap 192.168.1.1 --script http* | Run scripts by name or wildcard |
--script <script1>,<script2> | nmap --script banner,http-title | Run specific scripts |
--script-args | nmap --script snmp-sysdescr --script-args snmpcommunity=public | Provide args to scripts |
--script "not intrusive" | nmap --script "default and not intrusive" | Compose script sets (example) |
Useful NSE Examples
A few practical one-liners to keep handy.
# Generate sitemap from web server (HTTP):
nmap -Pn --script=http-sitemap-generator scanme.nmap.org
# Fast random search for web servers:
nmap -n -Pn -p 80 --open -sV -vvv --script banner,http-title -iR 1000
# Brute-force DNS hostnames (subdomain guessing):
nmap -Pn --script=dns-brute domain.com
# Safe SMB enumeration (useful on internal networks):
nmap -n -Pn -vv -O -sV --script smb-enum*,smb-ls,smb-mbenum,smb-os-discovery,smb-vuln* 192.168.1.1
# Whois queries via scripts:
nmap --script whois* domain.com
# Detect XSS-style unsafe output escaping on HTTP port 80:
nmap -p80 --script http-unsafe-output-escaping scanme.nmap.org
# Check for SQL injection (scripted):
nmap -p80 --script http-sql-injection scanme.nmap.org
Firewall / IDS Evasion & Spoofing
Techniques to make traffic less obvious. Use responsibly.
| Switch | Example | Description |
|---|---|---|
-f | nmap 192.168.1.1 -f | Fragment packets (can evade some filters) |
--mtu | nmap 192.168.1.1 --mtu 32 | Set MTU/fragment size |
-D | nmap -D decoy1,decoy2,ME,decoy3 target | Decoy IP addresses to confuse observers |
-S | nmap -S 1.2.3.4 target | Spoof source IP (may require raw sockets) |
-g | nmap -g 53 target | Set source port (useful to bypass simple filters) |
--proxies | nmap --proxies http://192.168.1.1:8080 target | Relay scans through HTTP/SOCKS proxies |
--data-length | nmap --data-length 200 target | Append random data to packets |
Example IDS evasion command
nmap -f -T0 -n -Pn --data-length 200 -D 192.168.1.101,192.168.1.102,192.168.1.103,192.168.1.23 192.168.1.1
Output Formats & Options
Save scans so you can analyze later or process programmatically.
| Switch | Example | Description |
|---|---|---|
-oN | nmap 192.168.1.1 -oN normal.file | Normal human-readable output file |
-oX | nmap 192.168.1.1 -oX xml.file | XML output (good for parsing) |
-oG | nmap 192.168.1.1 -oG grep.file | Grepable output (legacy) |
-oA | nmap 192.168.1.1 -oA results | Write results.nmap, results.xml, results.gnmap |
-oG - | nmap 192.168.1.1 -oG - | Print grepable to stdout |
--append-output | nmap -oN file -append-output | Append to an existing file |
-v / -vv | nmap -v | Increase verbosity |
-d / -dd | nmap -d | Increase debugging info |
--reason | nmap --reason | Show reason a port state was classified |
--open | nmap --open | Show only open or possibly-open ports |
--packet-trace | nmap --packet-trace | Show raw packet send/receive detail |
--iflist | nmap --iflist | List interfaces and routes |
--resume | nmap --resume results.file | Resume an interrupted scan (requires prior save) |
Helpful Output Examples & Pipelines
Combine Nmap with standard UNIX tools to extract actionable info.
# Find web servers (HTTP):
nmap -p80 -sV -oG - --open 192.168.1.0/24 | grep open
# Generate list of live hosts from random scan (XML -> grep -> cut):
nmap -iR 10 -n -oX out.xml | grep "Nmap" | cut -d " " -f5 > live-hosts.txt
# Append hosts from second scan:
nmap -iR 10 -n -oX out2.xml | grep "Nmap" | cut -d " " -f5 >> live-hosts.txt
# Compare two scans:
ndiff scan1.xml scan2.xml
# Convert XML to HTML:
xsltproc nmap.xml -o nmap.html
# Frequency of open ports (clean and aggregate):
grep " open " results.nmap | sed -r 's/ +/ /g' | sort | uniq -c | sort -rn | less
Miscellaneous Flags
| Switch | Example | Description |
|---|---|---|
-6 | nmap -6 2607:f0d0:1002:51::4 | Enable IPv6 scanning |
-h | nmap -h | Show help screen |
Other Useful Commands (Mixed Examples)
# Discovery only on specific TCP ports, no port scan:
nmap -iR 10 -PS22-25,80,113,1050,35000 -v -sn
# ARP-only discovery on local net, verbose, no port scan:
nmap 192.168.1.0/24 -PR -sn -vv
# Traceroute to random targets (no ports):
nmap -iR 10 -sn --traceroute
# List targets only but use internal DNS server:
nmap 192.168.1.1-50 -sL --dns-server 192.168.1.1
# Show packet details during scan:
nmap 192.168.1.1 --packet-trace
Practical Tips & Etiquette
- Always have written permission to scan networks you do not own.
- Start small: discovery -> targeted port scan -> version detection -> scripts.
- Use
--scriptcarefully; some scripts are intrusive. - Keep a log of what you scanned and when (timestamps help with audits).
- For large networks, break scans into chunks and use
--min-rate/--max-rateto control load.
Appendix β Quick Command Generator (Examples)
nmap -sS -p 1-100 -T4 -oA quick-scan 192.168.1.0/24β fast SYN scan of top 100 ports, save outputs.nmap -Pn -sV --script=vuln -oX vuln-check.xml 10.0.0.5β skip host discovery, version & vulnerability scripts.
SSH Cheat Sheet
Whether you need a quick recap of SSH commands or youβre learning SSH from scratch, this guide will help. SSH is a must-have tool for network administrators and anyone who needs to log in to remote systems securely.
π What Is SSH?
SSH (Secure Shell / Secure Socket Shell) is a network protocol that allows secure access to network services over unsecured networks.
Key tools included in the suite:
- ssh-keygen β Create SSH authentication key pairs.
- scp (Secure Copy Protocol) β Copy files securely between hosts.
- sftp (Secure File Transfer Protocol) β Securely send/receive files.
By default, an SSH server listens on TCP port 22.
π Basic SSH Commands
| Command | Description |
|---|---|
ssh user@host | Connect to remote server |
ssh pi@raspberry | Connect as pi on default port 22 |
ssh pi@raspberry -p 3344 | Connect on custom port 3344 |
ssh -i /path/file.pem admin@192.168.1.1 | Connect using private key file |
ssh root@192.168.2.2 'ls -l' | Execute remote command |
ssh user@192.168.3.3 bash < script.sh | Run script remotely |
ssh friend@Best.local "tar cvzf - ~/ffmpeg" > output.tgz | Download compressed directory |
π Key Management
| Command | Description |
|---|---|
ssh-keygen | Generate SSH keys |
ssh-keygen -F [host] | Find entry in known_hosts |
ssh-keygen -R [host] | Remove entry from known_hosts |
ssh-keygen -y -f private.key > public.pub | Generate public key from private |
ssh-keygen -t rsa -b 4096 -C "email@example.com" | Generate new RSA 4096-bit key |
π File Transfers
SCP (Secure Copy)
| Command | Description |
|---|---|
scp user@server:/file dest/ | Copy remote β local |
scp file user@server:/path | Copy local β remote |
scp user1@server1:/file user2@server2:/path | Copy between two servers |
scp -r user@server:/folder dest/ | Copy directory recursively |
scp -P 8080 file user@server:/path | Connect on port 8080 |
scp -C | Enable compression |
scp -v | Verbose output |
SFTP (Secure File Transfer)
| Command | Description |
|---|---|
sftp user@server | Connect to server via SFTP |
sftp -P 8080 user@server | Connect on port 8080 |
sftp -r dir user@server:/path | Recursively transfer directory |
βοΈ SSH Configurations & Options
| Command | Description |
|---|---|
man ssh_config | SSH client configuration manual |
cat /etc/ssh/ssh_config | View system-wide SSH client config |
cat /etc/ssh/sshd_config | View system-wide SSH server config |
cat ~/.ssh/config | View user-specific config |
cat ~/.ssh/known_hosts | View logged-in hosts |
SSH Agent & Keys
| Command | Description |
|---|---|
ssh-agent | Start agent to hold private keys |
ssh-add ~/.ssh/id_rsa | Add key to agent |
ssh-add -l | List cached keys |
ssh-add -D | Delete all cached keys |
ssh-copy-id user@server | Copy keys to remote server |
π₯οΈ Remote Server Management
After logging into a remote server:
cdβ Change directorylsβ List filesmkdirβ Create directorymvβ Move/rename filesnano/vimβ Edit filespsβ List processeskillβ Stop processtopβ Monitor resourcesexitβ Close SSH session
π Advanced SSH Commands
X11 Forwarding (GUI Apps over SSH)
-
Client
~/.ssh/config:Host * ForwardAgent yes ForwardX11 yes -
Server
/etc/ssh/sshd_config:X11Forwarding yes X11DisplayOffset 10 X11UseLocalhost no
| Command | Description |
|---|---|
sshfs user@server:/path /local/mount | Mount remote filesystem locally |
ssh -C user@host | Enable compression |
ssh -X user@server | Enable X11 forwarding |
ssh -Y user@server | Enable trusted X11 forwarding |
π SSH Tunneling
Local Port Forwarding -L
ssh -L local_port:destination:remote_port user@server
Example: ssh -L 2222:10.0.1.5:3333 root@192.168.0.1
Remote Port Forwarding -R
ssh -R remote_port:destination:destination_port user@server
Example: ssh -R 8080:192.168.3.8:3030 -N -f user@remote.host
Dynamic Port Forwarding -D (SOCKS Proxy)
ssh -D 6677 -q -C -N -f user@host
ProxyJump -J (Bastion Host)
ssh -J user@proxy_host user@target_host
π‘οΈ Security Best Practices
- Disable unused features:
AllowTcpForwarding no,X11Forwarding no. - Change default port from
22to something else. - Use SSH certificates with
ssh-keygen. - Restrict logins with
AllowUsersinsshd_config. - Use bastion hosts for added security.
β Conclusion
This cheat sheet covered:
- Basic SSH connections
- File transfers (SCP/SFTP)
- Key management & configs
- Remote management commands
- Advanced tunneling & forwarding
SSH remains an indispensable tool for IT professionals and security practitioners.
Wireshark Cheat Sheet
Wireshark is one of the most popular and powerful tools for capturing, analyzing, and troubleshooting network traffic.
Whether you are a network administrator, security professional, or just someone curious about how networks work, learning Wireshark is a valuable skill. This cheat sheet serves as a quick reference for filters, commands, shortcuts, and syntax.
π Default Columns in Packet Capture
| Name | Description |
|---|---|
| No. | Frame number from the beginning of the packet capture |
| Time | Seconds from the first frame |
| Source (src) | Source address (IPv4, IPv6, or Ethernet) |
| Destination (dst) | Destination address |
| Protocol | Protocol in Ethernet/IP/TCP segment |
| Length | Frame length in bytes |
π Logical Operators
| Operator | Description | Example | ||
|---|---|---|---|---|
and / && | Logical AND | All conditions must match | ||
or / ` | ` | Logical OR | At least one condition matches | |
xor / ^^ | Logical XOR | Only one of two conditions matches | ||
not / ! | Negation | Exclude packets | ||
[n] [ ... ] | Substring operator | Match specific text |
π― Filtering Packets (Display Filters)
| Operator | Description | Example |
|---|---|---|
eq / == | Equal | ip.dest == 192.168.1.1 |
ne / != | Not equal | ip.dest != 192.168.1.1 |
gt / > | Greater than | frame.len > 10 |
lt / < | Less than | frame.len < 10 |
ge / >= | Greater or equal | frame.len >= 10 |
le / <= | Less or equal | frame.len <= 10 |
π§© Filter Types
| Name | Description |
|---|---|
| Capture filter | Applied during capture |
| Display filter | Applied to hide/show after capture |
π‘ Capturing Modes
| Mode | Description |
|---|---|
| Promiscuous mode | Capture all packets on the segment |
| Monitor mode | Capture all wireless traffic (Linux/Unix only) |
β‘ Miscellaneous
- Slice Operator β
[ ... ](range) - Membership Operator β
{}(in) - Ctrl+E β Start/Stop capturing
π Capture Filter Syntax
Example:
tcp src 192.168.1.1 and tcp dst 202.164.30.1
π¨ Display Filter Syntax
Example:
http and ip.dst == 192.168.1.1 and tcp.port
β¨οΈ Keyboard Shortcuts (Main Window)
| Shortcut | Action |
|---|---|
Tab / Shift+Tab | Move between UI elements |
β / β | Move between packets/details |
Ctrl+β / F8 | Next packet (even if unfocused) |
Ctrl+β / F7 | Previous packet |
Ctrl+. | Next packet in conversation |
Ctrl+, | Previous packet in conversation |
Return / Enter | Toggle tree item |
Backspace | Jump to parent node |
π Protocol Values
ether, fddi, ip, arp, rarp, decnet, lat, sca, moprc, mopdl, tcp, udp
π Common Filtering Commands
| Usage | Syntax |
|---|---|
| Filter by IP | ip.addr == 10.10.50.1 |
| Destination IP | ip.dest == 10.10.50.1 |
| Source IP | ip.src == 10.10.50.1 |
| IP range | ip.addr >= 10.10.50.1 and ip.addr <= 10.10.50.100 |
| Multiple IPs | ip.addr == 10.10.50.1 and ip.addr == 10.10.50.100 |
| Exclude IP | !(ip.addr == 10.10.50.1) |
| Subnet | ip.addr == 10.10.50.1/24 |
| Port | tcp.port == 25 |
| Destination port | tcp.dstport == 23 |
| IP + Port | ip.addr == 10.10.50.1 and tcp.port == 25 |
| URL | http.host == "hostname" |
| Time | frame.time >= "June 02, 2019 18:04:00" |
| SYN flag | tcp.flags.syn == 1 and tcp.flags.ack == 0 |
| Beacon frames | wlan.fc.type_subtype == 0x08 |
| Broadcast | eth.dst == ff:ff:ff:ff:ff:ff |
| Multicast | (eth.dst[0] & 1) |
| Hostname | ip.host == hostname |
| MAC address | eth.addr == 00:70:f4:23:18:c4 |
| RST flag | tcp.flag.reset == 1 |
π οΈ Main Toolbar Items
| Icon | Item | Menu | Description |
|---|---|---|---|
| βΆοΈ | Start | Capture β Start | Begin capture |
| βΉοΈ | Stop | Capture β Stop | Stop capture |
| π | Restart | Capture β Restart | Restart session |
| βοΈ | Options | Capture β Optionsβ¦ | Capture options dialog |
| π | Open | File β Openβ¦ | Load capture file |
| πΎ | Save As | File β Save Asβ¦ | Save capture file |
| β | Close | File β Close | Close current capture |
| π | Reload | View β Reload | Reload capture file |
| π | Find Packet | Edit β Find Packetβ¦ | Search packets |
| βͺ | Go Back | Go β Back | Jump back in history |
| β© | Go Forward | Go β Forward | Jump forward |
| π | Go to Packet | Go β Packet | Jump to specific packet |
| β©οΈ | First Packet | Go β First Packet | Jump to first packet |
| βͺοΈ | Last Packet | Go β Last Packet | Jump to last packet |
| π | Auto Scroll | View β Auto Scroll | Scroll live capture |
| π¨ | Colorize | View β Colorize | Colorize packet list |
| π | Zoom In/Out | View β Zoom In/Out | Adjust zoom level |
| π² | Normal Size | View β Normal Size | Reset zoom |
| π | Resize Columns | View β Resize Columns | Fit column width |
β Conclusion
Wireshark is an incredibly powerful tool for analyzing and troubleshooting network traffic. This cheat sheet gives you commands, filters, and shortcuts to navigate Wireshark efficiently and quickly.
Google Search β One-page cheat-sheet
A compact, copy-pasteable markdown cheat-sheet with short explanations and ready examples.
Core operators (fast, precise)
-
related:β Find sites similar to a domain. Example:related:clientwebsite.com -
site:β Search only inside a specific website. Example:burnout at work site:hbr.org -
intitle:infographicβ Pages that call out βinfographicβ in the title. Example:gdpr intitle:infographic -
filetype:β Restrict results to a file format (pdf, docx, ppt). Example:consulting case interview filetype:pdf -
intitle:2022β Find pages with a specific year in the title (good for reviews). Example:intitle:2022 laptop for students -
-(minus) β Exclude words to reduce noise. Example:meta -facebook -
-site:β Exclude an entire domain. Example:data visualization -site:youtube.com -site:pinterest.com -
"exact phrase"β Exact-match a full phrase. Example:"that's where google must be down" -
*(wildcard) β Placeholder for unknown words. Example:"top * programming languages 2024" -
+β Force inclusion / niche focus. Example:app annie +shopping -
ORβ Return results that match either term. Example:growth marketing OR content marketing OR product marketing
Region & time filters
-
Country TLD with
site:β Limit to country-level domains. Example:vaccine site:.usorvaccine site:.fr -
Date tools (Google β Tools β Any time) β Filter by recency (e.g., Past year). Example workflow: Search
google tasks tipsβ Tools β selectPast year
Image quick tip
- Transparent backgrounds β Images β Tools β Color β Transparent.
Example:
company logoβ Tools β Color β Transparent
Quick reference (your numbered list mapped to operators)
- Exact search:
"search" - Site search:
site: - Exclude:
-search - After date:
after:YYYY-MM-DD(useful for single-date filtering) - Range:
YYYY-MM-DD..YYYY-MM-DD(orfirst..secondfor numbers) - Compare / either/or:
(A|B) CorA OR B C - Wildcard:
*search(use*inside phrases) - File type:
filetype:pdf
Combine operators β practical combos
-
Find recent PDFs from universities:
site:edu filetype:pdf intitle:2023 -
Search product reviews excluding YouTube:
"laptop review" intitle:2024 -site:youtube.com -
Regional news about vaccines:
vaccine site:.de after:2024-01-01 -
Narrow Q&A on a topic:
"how to build REST API" site:stackoverflow.com
Copy-paste cheat block
related:clientwebsite.com
burnout at work site:hbr.org
gdpr intitle:infographic
consulting case interview filetype:pdf
intitle:2022 laptop for students
meta -facebook
data visualization -site:youtube.com -site:pinterest.com
"that's where google must be down"
"top * programming languages 2024"
app annie +shopping
growth marketing OR content marketing OR product marketing
vaccine site:.us