Python Algorithms Explained: Sorting, Searching, Graphs, Dynamic Programming and Data Structures
Python Algorithms Explained is a readable collection of 56 classic algorithms and data structures written in clean, modern Python, each with a plain-English explanation, its time and space complexity, and pytest tests. It is for students learning data structures and algorithms (DSA), developers preparing for coding interviews, and anyone who wants to see how merge sort, binary search, Dijkstra, A*, dynamic programming, a segment tree or a trie actually work without wading through clever one-liners.
Every file is short enough to read in one sitting, uses only the Python standard library, and starts with a docstring that answers three questions: what is the idea, how fast is it, and when would I use it.
Last reviewed: December 2026
Table of contents
- Why this repo
- Quick start
- Project layout
- How to read an algorithm file
- Algorithm index
- Short explanations
- Step-by-step walkthroughs
- Comparison tables and best picks
- Sorting: which one wins?
- Searching a sorted list
- Shortest paths: BFS vs Dijkstra vs A* vs Bellman-Ford vs Floyd-Warshall
- Minimum spanning tree: Kruskal vs Prim
- Substring search: naive vs KMP vs Z vs Rabin-Karp
- Range queries: prefix sums vs Fenwick tree vs segment tree
- Primality: trial division vs sieve vs Miller-Rabin
- The standard library already has these
- Suggested learning order
- Big-O cheat sheet
- Choosing the right algorithm
- Common mistakes these files avoid
- Exercises
- FAQ
- Where to go next
- Contributing
- License
- More free resources
Why this repo
- Explanation first. Each module’s docstring explains the intuition before you see a line of code, then states the complexity and when the algorithm is a good or bad choice.
- One idea per file. No frameworks, no inheritance trees, no helper modules you have to chase. The only cross-file import is Kruskal reusing the union-find structure, which is the point of union-find.
- Tested. 126 pytest tests check normal cases, edge cases (empty input, duplicates, negative numbers, cycles), and compare against Python’s built-ins or a slower reference on random data where that helps.
- Standard library only. Python 3.10 or newer is all you need to read and run the code. pytest is only needed to run the tests.
- Idiomatic Python. Type hints,
dataclassnodes, generators for traversals, andheapq/bisect/collectionswhere a real Python programmer would use them.
Quick start
git clone https://github.com/Ralpberry-Labs/python-algorithms-explained.git
cd python-algorithms-explained
# optional: a virtual environment for pytest
python3 -m venv .venv
source .venv/bin/activate
pip install pytest
pytest # runs all tests (configured in pyproject.toml)
pytest tests/test_graphs.py -v # just one topic, verbose
pytest -k dijkstra # tests whose name matches "dijkstra"
Use an algorithm from a Python shell started in the repo root:
>>> from algorithms.sorting.merge_sort import merge_sort
>>> merge_sort([5, 2, 9, 1])
[1, 2, 5, 9]
>>> from algorithms.graphs.dijkstra import dijkstra
>>> graph = {"s": [("a", 1), ("b", 4)], "a": [("b", 2)], "b": []}
>>> dijkstra(graph, "s")
{'s': 0, 'a': 1, 'b': 3}
>>> from algorithms.dynamic_programming.edit_distance import edit_distance
>>> edit_distance("kitten", "sitting")
3
>>> from algorithms.dynamic_programming.matrix_chain_multiplication import matrix_chain_order
>>> matrix_chain_order([10, 30, 5, 60])
(4500, '((AB)C)')
Read the explanation for any module without opening the file:
python3 -c "import algorithms.graphs.a_star as m; help(m)"
Project layout
python-algorithms-explained/
├── algorithms/
│ ├── sorting/ 10 sorting algorithms
│ ├── searching/ 5 search and selection algorithms
│ ├── graphs/ 11 graph algorithms
│ ├── dynamic_programming/ 8 DP classics
│ ├── strings/ 6 string algorithms
│ ├── maths/ 6 number theory algorithms
│ └── data_structures/ 10 data structures
├── tests/ one test file per folder
├── pyproject.toml pytest configuration
└── README.md
The maths folder is called maths, not math, so it can never shadow Python’s built-in math module.
Graphs are plain dictionaries so you can type them by hand:
unweighted = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
weighted = {"A": [("B", 4), ("C", 1)], "B": [], "C": [("B", 2)]}
How to read an algorithm file
Every module follows the same shape:
- Idea: the intuition in a few sentences, often with the one invariant that makes the algorithm correct.
- Complexity: time and space, with best/average/worst case when they differ.
- When to use or Pitfalls: where the algorithm shines and where it breaks.
- Code: a short, typed implementation with comments only where a line is not obvious.
A good way to study: read the docstring, close the file, write the function yourself, then run the matching test file against your version.
Algorithm index
Complexities use n for input size, V and E for vertices and edges, m for pattern length, k for value range, W for knapsack capacity and L for key length.
Sorting
| Algorithm | Time (average) | Time (worst) | Extra space | Stable | File |
|---|---|---|---|---|---|
| Bubble sort | O(n²) | O(n²) | O(1) | Yes | bubble_sort.py |
| Selection sort | O(n²) | O(n²) | O(1) | No | selection_sort.py |
| Insertion sort | O(n²) | O(n²) | O(1) | Yes | insertion_sort.py |
| Shell sort (Ciura gaps) | about O(n^1.3) in practice | no tight bound known | O(1) | No | shell_sort.py |
| Merge sort | O(n log n) | O(n log n) | O(n) | Yes | merge_sort.py |
| Quick sort | O(n log n) | O(n²) | O(log n) | No | quick_sort.py |
| Heap sort | O(n log n) | O(n log n) | O(1) | No | heap_sort.py |
| Counting sort | O(n + k) | O(n + k) | O(n + k) | Yes | counting_sort.py |
| Radix sort (LSD) | O(d(n + b)) | O(d(n + b)) | O(n + b) | Yes | radix_sort.py |
| Bucket sort | O(n) for uniform data | O(n log n) here | O(n) | Yes | bucket_sort.py |
Searching and selection
| Algorithm | Time | Space | Requires | File |
|---|---|---|---|---|
| Linear search | O(n) | O(1) | Nothing | linear_search.py |
| Binary search, lower/upper bound | O(log n) | O(1) | Sorted input | binary_search.py |
| Exponential (galloping) search | O(log i) | O(1) | Sorted input | exponential_search.py |
| Interpolation search | O(log log n) expected, O(n) worst | O(1) | Sorted, evenly spread numbers | interpolation_search.py |
| Quickselect (k-th smallest) | O(n) expected | O(n) | Nothing | quickselect.py |
Graphs
| Algorithm | Solves | Time | Space | File |
|---|---|---|---|---|
| Breadth-first search | Traversal, fewest-edge paths | O(V + E) | O(V) | breadth_first_search.py |
| Depth-first search | Traversal, directed cycle detection | O(V + E) | O(V) | depth_first_search.py |
| Bipartite check | Two-colouring, odd-cycle detection | O(V + E) | O(V) | bipartite.py |
| Topological sort (Kahn) | Order a DAG, detect cycles | O(V + E) | O(V) | topological_sort.py |
| Strongly connected components (Kosaraju) | Groups of mutually reachable nodes | O(V + E) | O(V + E) | strongly_connected_components.py |
| Dijkstra | Single-source shortest paths, weights ≥ 0 | O((V + E) log V) | O(V + E) | dijkstra.py |
| A* search | Point-to-point shortest path with a heuristic | O(E log V) worst | O(V) | a_star.py |
| Bellman-Ford | Shortest paths with negative weights | O(V·E) | O(V) | bellman_ford.py |
| Floyd-Warshall | All-pairs shortest paths | O(V³) | O(V²) | floyd_warshall.py |
| Kruskal | Minimum spanning tree (edge list) | O(E log E) | O(V) | kruskal.py |
| Prim | Minimum spanning tree (adjacency list) | O(E log V) | O(V + E) | prim.py |
Dynamic programming
| Problem | Time | Space | File |
|---|---|---|---|
| Fibonacci (naive, memoised, bottom-up) | O(n) | O(1) | fibonacci.py |
| 0/1 knapsack | O(n·W) | O(W) | knapsack.py |
| Subset sum, equal partition | O(n·target) | O(target) | subset_sum.py |
| Coin change (min coins, count ways) | O(amount·coins) | O(amount) | coin_change.py |
| Longest increasing subsequence | O(n log n) | O(n) | longest_increasing_subsequence.py |
| Longest common subsequence | O(m·n) | O(m·n) | longest_common_subsequence.py |
| Edit (Levenshtein) distance | O(m·n) | O(n) | edit_distance.py |
| Matrix chain multiplication | O(n³) | O(n²) | matrix_chain_multiplication.py |
Strings
| Algorithm | Time | Space | File |
|---|---|---|---|
| Knuth-Morris-Pratt search | O(n + m) | O(m) | kmp.py |
| Z-algorithm | O(n + m) | O(n + m) | z_algorithm.py |
| Rabin-Karp search | O(n + m) expected | O(1) | rabin_karp.py |
| Longest palindromic substring (expand around centre) | O(n²) | O(1) | longest_palindromic_substring.py |
| Manacher’s algorithm | O(n) | O(n) | manacher.py |
| Anagram check and grouping | O(n) / O(N·k log k) | O(n) | anagrams.py |
Maths and number theory
| Algorithm | Time | Space | File |
|---|---|---|---|
| GCD, LCM, extended Euclid | O(log min(a, b)) | O(1) | gcd_lcm.py |
| Sieve of Eratosthenes | O(n log log n) | O(n) | sieve_of_eratosthenes.py |
| Fast (binary) exponentiation | O(log n) | O(1) | fast_power.py |
| Prime factorisation, trial-division primality | O(√n) | O(log n) | prime_factorization.py |
| Miller-Rabin primality (deterministic for 64-bit) | O(k log³ n) | O(1) | miller_rabin.py |
| Binomial coefficients (Pascal, n choose k mod p) | O(n²) / O(k + log p) | O(n) / O(1) | binomial_coefficient.py |
Data structures
| Structure | Key operations | Cost | File |
|---|---|---|---|
| Stack (+ balanced brackets) | push, pop, peek | O(1) amortised | stack.py |
| Queue from two stacks | enqueue, dequeue | O(1) amortised | queue.py |
| Singly linked list | push_front, append, remove, reverse | O(1) / O(n) | linked_list.py |
| Binary search tree | insert, search, delete, in-order | O(h) | binary_search_tree.py |
| Binary min-heap | push, pop, peek, heapify | O(log n) / O(1) / O(n) | min_heap.py |
| Union-find (DSU) | find, union | O(α(n)) amortised | union_find.py |
| Trie (prefix tree) | insert, contains, prefix search | O(L) | trie.py |
| LRU cache | get, put | O(1) | lru_cache.py |
| Fenwick tree (binary indexed tree) | point add, prefix/range sum | O(log n) | fenwick_tree.py |
| Segment tree | point update, range min/sum/any associative op | O(log n) | segment_tree.py |
Short explanations
These are the one-paragraph versions. The full explanation is at the top of each file.
Sorting
Bubble sort swaps neighbours that are out of order; after each pass the largest remaining value has reached the end. Its one redeeming feature is the early exit: a pass with no swaps proves the list is sorted, so already-sorted input takes O(n).
Selection sort finds the minimum of the unsorted part and swaps it into place. It always does O(n²) comparisons but at most n - 1 swaps, which matters only when writing is far more expensive than reading.
Insertion sort grows a sorted prefix, sliding each new element left until it fits. It is fast on small or nearly sorted data, which is why hybrid sorts such as Timsort (behind Python’s sorted) use it on short runs.
Shell sort runs insertion sort on elements that are a “gap” apart, for a shrinking sequence of gaps ending at 1. Far-away elements move long distances early, so the final gap-1 pass has little left to do. It needs no recursion and no extra memory.
Merge sort splits the list in half, sorts both halves and merges them. The merge step is the reusable idea: two sorted sequences can be combined in linear time by repeatedly taking the smaller head.
Quick sort picks a pivot, partitions everything smaller to the left and everything else to the right, and recurses. This version picks a random pivot, keeps working on the smaller side and defers the larger side on an explicit stack, so that stack never holds more than O(log n) ranges.
Heap sort turns the array into a max-heap in O(n) and then repeatedly swaps the root (the maximum) to the end. It is in place and always O(n log n), but jumps around memory, so it is usually slower than quick sort in practice.
Counting sort does not compare at all. It counts how many times each key appears and uses prefix sums to place each item directly. Walking the input backwards keeps it stable.
Radix sort sorts integers digit by digit, least significant first, with a stable pass per digit. Stability is the whole trick: ties in the current digit keep the order produced by earlier digits.
Bucket sort spreads values over n equal-width buckets, sorts each small bucket and concatenates them. It is linear on average when the values are spread evenly.
Searching
Linear search checks each element in turn. It is the right answer for unsorted data you will only search once.
Binary search halves a sorted range each step. The file implements lower_bound (first index with value ≥ target) and upper_bound (first index with value > target), which answer “where would this go?” and “how many copies are there?” as well as “is it here?”.
Exponential search doubles an index (1, 2, 4, 8, …) until it passes the target and then binary-searches that window. Its cost depends on how far the target is from the start, which helps with very long or unbounded sorted data.
Interpolation search guesses the position from the value itself, like opening a dictionary near the end for a word starting with “w”. On evenly spread numbers it needs about log log n probes; on skewed data it can degrade to a linear scan.
Quickselect finds the k-th smallest element by partitioning like quick sort but following only the side that contains position k, for linear expected time.
Graphs
BFS explores in layers using a queue, so the first time it reaches a node it has used the fewest possible edges. Mark nodes visited when you enqueue them.
DFS follows one branch as deep as it goes before backtracking. The three-colour version (white, grey, black) detects cycles in directed graphs: meeting a grey node means you have looped back onto the current path.
Bipartite check colours nodes alternately with BFS. An edge between two nodes of the same colour proves there is an odd cycle, so no two-group split exists.
Topological sort orders tasks so every prerequisite comes first. Kahn’s algorithm repeatedly removes nodes with no incoming edges; leftovers mean a cycle.
Strongly connected components (Kosaraju) runs DFS once to get finishing order, reverses every edge, then runs DFS again in reverse finishing order. Each second-pass DFS collects exactly one component.
Dijkstra always expands the closest unfinished node, using a heap. With non-negative weights that node’s distance is final. Old heap entries are skipped when popped instead of being updated in place.
A* is Dijkstra with a sense of direction: it orders nodes by distance so far plus an estimate of the distance left. If the estimate never overestimates, the path is still optimal and far fewer nodes are explored.
Bellman-Ford relaxes every edge V - 1 times, which is enough for any shortest path. One more successful relaxation proves a negative cycle exists.
Floyd-Warshall asks, for each node k in turn, “does going through k make any i-to-j path shorter?” Three nested loops give every pairwise distance.
Kruskal adds edges from lightest to heaviest, skipping any that would close a cycle, which union-find detects almost instantly.
Prim grows a single tree outward, always taking the cheapest edge that reaches a new node.
Dynamic programming
Fibonacci shows the core DP move three ways: the exponential recursive tree, the same recursion with a cache, and a two-variable loop.
0/1 knapsack fills a table indexed by capacity. Looping capacities downwards is what stops an item being used twice.
Subset sum tracks which totals are reachable. The file also shows the Python trick of storing the whole reachable set as bits of one integer (bits |= bits << x), which is often much faster.
Coin change computes the fewest coins for every amount up to the target. It also shows why greedy is wrong for some coin sets, and how loop order decides whether you count combinations or orderings.
Longest increasing subsequence keeps the smallest possible tail for each length and binary-searches it, for O(n log n).
Longest common subsequence fills a 2-D table where each cell depends on its left, upper and upper-left neighbours, then walks back to rebuild the answer.
Edit distance counts the fewest insertions, deletions and substitutions between two strings, keeping only two rows of the table.
Matrix chain multiplication is the textbook interval DP: the best cost for a range is the best split point inside it. The same shape solves “burst balloons” and optimal binary search trees.
Strings
KMP precomputes, for each prefix of the pattern, the longest border (a prefix that is also a suffix). On a mismatch the pattern jumps ahead using that table and the text pointer never moves back.
The Z-algorithm computes, for every position, how long the substring starting there matches the prefix. Searching pattern + separator + text turns that into a linear-time pattern search.
Rabin-Karp compares rolling hashes of the pattern and each text window, and only compares characters when hashes match.
Longest palindromic substring expands outward from each of the 2n - 1 possible centres.
Manacher’s algorithm reuses the mirror image of palindromes already found, so the right edge of the explored area only moves forward: linear time.
Anagrams are detected by comparing letter counts and grouped by a canonical key (the sorted letters).
Maths
Euclid’s algorithm replaces (a, b) with (b, a mod b) until b is zero. The extended version also finds coefficients x and y with ax + by = gcd(a, b), the basis of modular inverses.
The sieve of Eratosthenes crosses out multiples of each prime starting at p², producing all primes up to n.
Fast exponentiation reads the exponent in binary, squaring the base each step, to compute large powers (mod m) in O(log n) multiplications.
Trial division factors n by testing divisors up to √n; whatever remains above 1 is prime.
Miller-Rabin checks a handful of bases for a “witness” that n is composite. With the first 13 primes as bases it gives the right answer for every 64-bit integer, and the tests include a Carmichael number and a strong pseudoprime that fool weaker tests.
Binomial coefficients are built with Pascal’s rule, or computed mod a prime using a modular inverse from Fermat’s little theorem.
Data structures
Stack: last in, first out. The bracket checker pushes openers and pops on each closer.
Queue from two stacks: push into an inbox, pop from an outbox, and pour the inbox into the outbox only when the outbox is empty. Each item moves at most twice.
Linked list: nodes and pointers; reversal is the classic three-pointer exercise.
Binary search tree: smaller keys left, larger keys right. In-order traversal yields sorted keys; deletion of a two-child node uses the in-order successor.
Min-heap: a complete binary tree stored in a list with sift-up and sift-down.
Union-find: groups as trees, with path compression and union by size.
Trie: one node per prefix, so prefix lookups cost the length of the prefix.
LRU cache: a hash map plus recency order, built here on OrderedDict.
Fenwick tree: each index stores the sum of a block whose length is its lowest set bit, so updates and prefix sums both walk O(log n) indices.
Segment tree: a tree of range answers stored in a flat array of size 2n. Pass any associative function (min, max, sum, gcd) and its identity value.
Step-by-step walkthroughs
Tracing an algorithm by hand on a tiny input is the fastest way to understand it. These traces were produced by running the code in this repo.
Binary search: lower_bound([1, 3, 3, 5, 8, 13, 21], 5)
The search space is the half-open range [lo, hi). Each step looks at mid and throws away half.
| Step | lo | hi | mid | items[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 7 | 3 | 5 | 5 ≥ 5, so the answer is at or left of 3: hi = 3 |
| 2 | 0 | 3 | 1 | 3 | 3 < 5, so the answer is right of 1: lo = 2 |
| 3 | 2 | 3 | 2 | 3 | 3 < 5: lo = 3 |
| end | 3 | 3 | lo == hi == 3, and items[3] == 5, so the target is found |
Three probes for seven items; a million items would need about twenty.
Merge sort: [5, 2, 9, 1, 7, 3]
split: [5, 2, 9, 1, 7, 3]
[5, 2, 9] [1, 7, 3]
[5] [2, 9] [1] [7, 3]
[2] [9] [7] [3]
merge: [2, 9] [3, 7]
[2, 5, 9] [1, 3, 7]
[1, 2, 3, 5, 7, 9]
There are about log₂(6) ≈ 3 levels, and each level does O(n) work merging, which is where O(n log n) comes from.
Dijkstra: shortest distances from s
Graph: s→a (1), s→b (4), a→b (2), a→c (6), b→c (3).
| Pop | Distance final? | Edges relaxed | Heap afterwards |
|---|---|---|---|
| (0, s) | s = 0 | a = 1, b = 4 | (1, a), (4, b) |
| (1, a) | a = 1 | b improves to 3, c = 7 | (3, b), (4, b), (7, c) |
| (3, b) | b = 3 | c improves to 6 | (4, b), (6, c), (7, c) |
| (4, b) | stale, skipped | none | (6, c), (7, c) |
| (6, c) | c = 6 | none | (7, c) |
| (7, c) | stale, skipped | none | empty |
Final distances: s = 0, a = 1, b = 3, c = 6. The stale entries show “lazy deletion”: instead of updating an entry inside the heap, push a better one and ignore the old one when it surfaces.
Edit distance: kitten → sitting
Each cell is the distance between a prefix of kitten (rows) and a prefix of sitting (columns). A cell copies its upper-left neighbour when the letters match; otherwise it is 1 + the minimum of its left, upper and upper-left neighbours.
| ”” | s | i | t | t | i | n | g | |
|---|---|---|---|---|---|---|---|---|
| ”“ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| k | 1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| i | 2 | 2 | 1 | 2 | 3 | 4 | 5 | 6 |
| t | 3 | 3 | 2 | 1 | 2 | 3 | 4 | 5 |
| t | 4 | 4 | 3 | 2 | 1 | 2 | 3 | 4 |
| e | 5 | 5 | 4 | 3 | 2 | 2 | 3 | 4 |
| n | 6 | 6 | 5 | 4 | 3 | 3 | 2 | 3 |
The bottom-right cell is 3: substitute k→s, substitute e→i, insert g.
Coin change with coins [1, 3, 4], amount 6
| Amount | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Fewest coins | 0 | 1 | 2 | 1 | 1 | 2 | 2 |
best[6] = 1 + min(best[5], best[3], best[2]) = 1 + 1 = 2 (3 + 3). Greedy would take 4 first and end with 4 + 1 + 1, three coins.
KMP prefix function for ababaca
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| pattern[i] | a | b | a | b | a | c | a |
| pi[i] | 0 | 0 | 1 | 2 | 3 | 0 | 1 |
pi[4] = 3 because aba is both a prefix of ababa and a suffix of it. When a match of ababa fails at the next character, KMP continues as if it had already matched aba, without moving back in the text.
Comparison tables and best picks
Big-O tells you how an algorithm scales; these tables add the practical trade-offs. Each ends with a best pick and the reason for it.
Sorting: which one wins?
| Situation | Best pick | Why | Avoid |
|---|---|---|---|
| Real Python code, any data | sorted() / list.sort() |
Timsort is written in C, stable, O(n log n), and very fast on partly sorted data | Any hand-written sort, which is far slower in pure Python |
| Learning how sorting works | Insertion sort, then merge sort | Insertion sort teaches invariants; merge sort teaches divide and conquer | Starting with heap sort before you know heaps |
| Must be stable | Merge sort | Stable and always O(n log n) | Quick sort, heap sort, selection sort |
| Little extra memory, guaranteed bound | Heap sort | O(1) extra space and O(n log n) worst case | Quick sort without a random pivot |
| Fastest general in-memory sort (in C, C++, Rust) | Tuned quick sort hybrids | Cache friendly; random or median pivots make the worst case unlikely | Naive first-element pivot |
| Small integers in a narrow range | Counting sort | O(n + k), no comparisons | Comparison sorts when k is tiny |
| Many fixed-width integer keys | Radix sort | O(d(n + b)) beats n log n when d is small | Radix sort on very long keys |
| Floats spread evenly | Bucket sort | Linear on average | Bucket sort on clustered data |
| Nearly sorted, small n | Insertion sort | O(n) on nearly sorted input | Selection sort, which is always O(n²) |
Best pick: use sorted() in real code; learn insertion sort and merge sort first because almost every other sort is a variation on their ideas.
Searching a sorted list
| Method | Probes for n = 10⁶ (roughly) | Good when | Weak when |
|---|---|---|---|
| Linear search | up to 1,000,000 | Data is unsorted or tiny | Repeated lookups on large data |
| Binary search | about 20 | Always a safe default on sorted data | Data is not sorted |
| Exponential search | about 2·log₂(i) | Target is near the front, length unknown | Target is near the end (slightly more probes than binary search) |
| Interpolation search | about 5 on evenly spread numbers | Uniform numeric keys | Skewed data, strings |
| Hash set / dict lookup | 1 on average | Only membership matters, no ordering | You need “closest” or range queries |
Best pick: bisect.bisect_left (the standard library’s binary search). Reach for a set instead if you never need ordering.
Shortest paths: BFS vs Dijkstra vs A* vs Bellman-Ford vs Floyd-Warshall
| Algorithm | Edge weights | Sources | Time | Detects negative cycles | Typical use |
|---|---|---|---|---|---|
| BFS | All equal | One | O(V + E) | n/a | Mazes, fewest hops, social distance |
| Dijkstra | Non-negative | One | O((V + E) log V) | No | Road networks, network routing |
| A* | Non-negative, plus a heuristic | One, to one goal | Often far less than Dijkstra | No | Games, maps, robotics |
| Bellman-Ford | Any | One | O(V·E) | Yes | Negative costs, arbitrage detection |
| Floyd-Warshall | Any (no negative cycles) | All pairs | O(V³) | Yes (negative diagonal) | Small dense graphs, transitive closure |
Best pick: BFS when every step costs the same, Dijkstra for one source with non-negative weights, A* when you have one goal and a good admissible heuristic. Only use Bellman-Ford when weights can actually be negative.
Minimum spanning tree: Kruskal vs Prim
| Kruskal | Prim | |
|---|---|---|
| Works on | Edge list | Adjacency list |
| Core structure | Sorting + union-find | Priority queue |
| Time | O(E log E) | O(E log V) with a binary heap |
| Handles disconnected graphs | Yes, returns a spanning forest | Only the start node’s component |
| Easiest to code from memory | Yes | Slightly more bookkeeping |
Best pick: Kruskal for sparse graphs and interviews (short, and union-find is useful elsewhere); Prim when the graph is dense and already stored as adjacency lists.
Substring search: naive vs KMP vs Z vs Rabin-Karp
| Algorithm | Worst case | Extra memory | Strength |
|---|---|---|---|
| Naive (check every position) | O(n·m) | O(1) | Fine for short patterns |
| KMP | O(n + m) | O(m) | Streams the text once, never moves backwards |
| Z-algorithm | O(n + m) | O(n + m) | Easiest linear-time method to derive; Z-array answers other prefix questions too |
| Rabin-Karp | O(n·m) (with many hash collisions), O(n + m) expected | O(1) | Many patterns of the same length at once; substring hashing |
Best pick: str.find or the in operator in real Python code (implemented in C and highly optimised). For interviews, learn KMP’s prefix function; it also solves “shortest repeating unit” and “longest prefix that is also a suffix” questions.
Range queries: prefix sums vs Fenwick tree vs segment tree
| Structure | Build | Point update | Range query | Supports | Code size |
|---|---|---|---|---|---|
| Prefix sum array | O(n) | O(n) | O(1) | Sums (invertible ops) | Tiny |
| Fenwick tree | O(n) | O(log n) | O(log n) | Sums and other invertible ops | Small |
| Segment tree | O(n) | O(log n) | O(log n) | Any associative op: min, max, gcd, sum | Medium |
Best pick: prefix sums if the array never changes; Fenwick tree for sums with updates; segment tree when you need min/max or anything that cannot be “subtracted”.
Primality: trial division vs sieve vs Miller-Rabin
| Method | Answers | Cost | Best for |
|---|---|---|---|
| Trial division | Is n prime? Factors of n | O(√n) | n up to about 10¹² in Python, and factorisation |
| Sieve of Eratosthenes | All primes up to N | O(N log log N) time, O(N) memory | Many queries below a few million |
| Miller-Rabin | Is n prime? | A few modular exponentiations | Large n, such as 64-bit integers |
Best pick: a sieve when you need many small primes, Miller-Rabin for one large number.
The standard library already has these
In production Python, prefer the built-in version: it is implemented in C, tested and maintained. This repo exists so you understand what they do.
| This repo | Standard library equivalent | Notes |
|---|---|---|
| Merge sort, quick sort, heap sort | sorted(), list.sort() |
Timsort; supports key= and reverse= |
| Binary search, lower/upper bound | bisect.bisect_left, bisect.bisect_right, bisect.insort |
key= parameter added in Python 3.10 |
| Min-heap, heap sort | heapq.heappush, heappop, heapify, nsmallest, nlargest, merge |
Min-heap only; negate keys for a max-heap |
| Queue | collections.deque |
O(1) at both ends |
| LRU cache | functools.lru_cache, functools.cache |
Decorators for memoising functions |
| Fibonacci memoisation | functools.cache |
Top-down DP in one line |
| Topological sort | graphlib.TopologicalSorter |
Added in Python 3.9 |
| GCD, LCM | math.gcd, math.lcm |
math.lcm added in Python 3.9 |
| Binomial coefficients | math.comb |
Added in Python 3.8 |
| Fast power, modular inverse | pow(base, exp, mod), pow(x, -1, mod) |
Three-argument pow is built in |
| Anagram counting | collections.Counter |
Multiset arithmetic and most_common |
| Substring search | str.find, str.index, in |
Optimised C implementation |
Suggested learning order
If you are new to algorithms, this order builds each idea on the previous one. Each step lists the files to read and the concept they teach.
| Step | Read | You learn |
|---|---|---|
| 1 | Linear search, binary search | Loop invariants, half-open ranges, why sorted data is powerful |
| 2 | Bubble, selection, insertion sort | Nested loops, swaps, best vs worst case |
| 3 | Merge sort | Recursion, divide and conquer, O(n log n) |
| 4 | Quick sort, quickselect | Partitioning, randomisation, expected running time |
| 5 | Stack, queue, linked list | Pointer manipulation, amortised analysis |
| 6 | Min-heap, heap sort | Array-backed trees, priority queues |
| 7 | Counting, radix, bucket, shell sort | Beating the comparison lower bound, stability, gap sequences |
| 8 | Binary search tree, trie | Tree recursion and traversal |
| 9 | GCD, sieve, fast power, factorisation | Number theory warm-ups, logarithmic loops |
| 10 | BFS, DFS, bipartite check | Graph representation, visited sets, cycle detection |
| 11 | Topological sort, union-find, SCC | Dependencies, connectivity, components |
| 12 | Dijkstra, A*, Bellman-Ford, Floyd-Warshall | Shortest paths, edge relaxation, heuristics |
| 13 | Kruskal, Prim | Greedy algorithms and why they are correct |
| 14 | Fibonacci, coin change, subset sum | The core DP pattern: state, transition, base case |
| 15 | Knapsack, LCS, edit distance, LIS | 1-D and 2-D DP tables, reconstructing answers |
| 16 | Matrix chain multiplication | Interval DP |
| 17 | KMP, Z-algorithm, Rabin-Karp, palindromes, Manacher, anagrams | String processing and hashing |
| 18 | Fenwick tree, segment tree | Range queries with updates |
| 19 | Miller-Rabin, binomial coefficients | Modular arithmetic at scale |
| 20 | LRU cache | Combining structures to hit O(1) everywhere |
For coding interviews, steps 1, 3, 5, 6, 8, 10, 11, 12 (Dijkstra), 14 and 15 cover most of what comes up. Fenwick and segment trees, Manacher and Miller-Rabin are more common in competitive programming than in interviews.
Big-O cheat sheet
From slowest-growing to fastest-growing, with a feel for what is practical at n = 1,000,000 on a typical machine running Python:
| Class | Name | Example in this repo | Practical at 10⁶? |
|---|---|---|---|
| O(1) | Constant | Stack push, LRU get | Yes |
| O(α(n)) | Inverse Ackermann | Union-find find | Yes |
| O(log log n) | Double logarithmic | Interpolation search (uniform data) | Yes |
| O(log n) | Logarithmic | Binary search, fast power, Fenwick query | Yes |
| O(√n) | Square root | Trial-division primality | Yes |
| O(n) | Linear | Linear search, quickselect, KMP, Manacher | Yes |
| O(n log n) | Linearithmic | Merge sort, heap sort | Yes |
| O(n²) | Quadratic | Insertion sort, edit distance | No (10¹² steps) |
| O(n³) | Cubic | Floyd-Warshall, matrix chain | Only for n in the hundreds |
| O(2ⁿ) | Exponential | Naive Fibonacci | Only for n around 30 |
Rules of thumb:
- Drop constants and lower-order terms: 3n² + 10n is O(n²).
- Nested loops over the same input usually multiply: two loops over n is O(n²).
- Halving the problem each step gives a log factor.
- “Amortised O(1)” means a single operation can be slow, but any sequence of k operations costs O(k) in total.
- Space complexity counts extra memory, including the recursion stack.
- “Pseudo-polynomial” (knapsack, subset sum) means polynomial in the value of a number, which is exponential in the number of digits used to write it.
Choosing the right algorithm
| You need to… | Reach for | Why |
|---|---|---|
| Sort anything in real code | sorted() / list.sort() |
Timsort is stable, O(n log n) and adaptive |
| Sort small integers with a small range | Counting sort | Linear time |
| Find something in sorted data | bisect / binary search |
O(log n) |
| Get the k smallest items | heapq.nsmallest or a heap |
O(n log k) |
| Get one order statistic (median) | Quickselect | O(n) expected |
| Shortest path, unweighted | BFS | O(V + E) |
| Shortest path, non-negative weights | Dijkstra | O((V + E) log V) |
| Shortest path to one goal on a map or grid | A* | Explores fewer nodes with a good heuristic |
| Shortest path, negative weights | Bellman-Ford | Handles negatives, detects negative cycles |
| Every pairwise distance, small graph | Floyd-Warshall | Three loops, easy to get right |
| Order tasks with dependencies | Topological sort | Also reports cycles |
| Find groups of mutually dependent nodes | Strongly connected components | Condenses a graph into a DAG |
| Split into two conflict-free groups | Bipartite check | BFS colouring |
| “Are these two connected?” many times | Union-find | Near O(1) per query |
| Cheapest way to connect everything | Kruskal or Prim | Minimum spanning tree |
| Range sums with updates | Fenwick tree | O(log n) each, tiny code |
| Range min/max with updates | Segment tree | Any associative operation |
| Prefix lookups / autocomplete | Trie | O(prefix length) |
| Find a pattern in text | str.find / in, or KMP |
KMP guarantees linear time |
| Longest palindrome in a long string | Manacher | O(n) |
| Is this 18-digit number prime? | Miller-Rabin | Trial division would take far too long |
| Fixed-size cache | LRU cache / functools.lru_cache |
O(1) get and put |
Common mistakes these files avoid
- Binary search off-by-one. The code sticks to one convention, a half-open range
[lo, hi)withwhile lo < hi, and returns insertion points instead of special values. - Marking BFS nodes visited too late. Marking on dequeue lets a node enter the queue many times; the files mark on enqueue.
- Quick sort on sorted input. A fixed first-element pivot makes sorted input quadratic and can overflow the stack. The file picks a random pivot and only defers the larger side.
- Dijkstra with negative weights. The function raises an error instead of silently returning wrong answers.
- Updating the heap in place. Dijkstra, Prim and A* push new entries and skip stale ones, which is simpler and just as fast in practice. A counter or the g-score breaks ties so nodes never need to be comparable.
- Recursion limits. Kosaraju’s first pass and the grid searches use explicit stacks or queues, so large inputs do not hit Python’s recursion limit.
- 0/1 knapsack loop direction. Iterating capacity upwards would let an item be used more than once; subset sum uses the same downward loop.
- Coin change by greedy. Greedy only works for some coin systems; the test with coins
[1, 3, 4]shows the failure. - Fermat-only primality tests. Carmichael numbers such as 561 fool the plain Fermat test; Miller-Rabin’s extra square-root check catches them, and the tests prove it.
- Mutable default arguments. None of the constructors use
[]or{}as default values. - Shadowing the standard library. The maths package is
maths, and the queue module is only ever imported asalgorithms.data_structures.queue.
Exercises
Try these once you have read the matching file. Each one changes a single idea.
- Make
bubble_sortsort in descending order by changing exactly one character. - Change
mergeto use<instead of<=, then write a test that proves it is no longer stable. - Rewrite
quick_sortwith the Hoare partition scheme and compare the number of swaps. - Add a
kth_largesthelper on top ofquickselect. - Extend
shortest_path(BFS) to work on a 2-D grid where#cells are walls, then compare the number of expanded cells witha_star. - Make
dijkstraalso return apreviousmap and rebuild the path to any node. - Turn the 0/1 knapsack into the unbounded knapsack, where each item can be used any number of times.
- Reconstruct the actual longest increasing subsequence, not just its length.
- Return the list of edit operations (insert, delete, substitute) from
edit_distance. - Add
delete(word)to the trie and prune nodes that no longer lead to a word. - Make
MinHeapaccept akeyfunction, likesorted. - Replace Kosaraju with Tarjan’s single-pass SCC algorithm and check both agree on random graphs.
- Add a
maxsegment tree and a “count of elements less than x in a range” query using a Fenwick tree over compressed values. - Use
comb_modto count lattice paths in an n × m grid modulo 10⁹ + 7 and compare withmath.comb. - Benchmark
subset_sumagainstsubset_sum_bitswithtimeitfor 100 numbers and a target of 100,000.
Write a test first for each exercise; the existing tests show the style.
FAQ
What sorting algorithm does Python use?
CPython’s list.sort() and sorted() use Timsort, a hybrid of merge sort and insertion sort that finds already-sorted runs in the data and merges them. The current implementation uses the “powersort” strategy to decide which runs to merge; the design notes are in Objects/listsort.txt in the CPython source. It is stable and O(n log n) in the worst case.
What is the fastest sorting algorithm?
There is no single winner. For general data in Python, the built-in sorted() beats any pure-Python sort by a wide margin. In theory, comparison sorts cannot beat O(n log n); counting, radix and bucket sort can be linear because they do not compare elements, but only for suitable keys. See Sorting: which one wins?.
What does “stable sort” mean and why does it matter? A stable sort keeps items with equal keys in their original order. It lets you sort by several keys in passes (sort by name, then stably by department) and it is what makes LSD radix sort correct.
Is Python too slow for algorithms and coding interviews?
No. Interviews judge the algorithm, not the constant factor, and Python’s built-ins (heapq, bisect, collections, functools.cache) make solutions short. In timed competitive programming, Python can be several times slower than C++, so some judges set separate time limits or you may need PyPy for heavy loops.
How do I make a max-heap in Python?
heapq only provides a min-heap. Push negated numbers (heapq.heappush(h, -x)) or tuples with a negated priority, and negate again when you pop.
What is the difference between BFS and DFS? BFS uses a queue and explores level by level, so it finds the fewest-edge path. DFS uses a stack (or recursion) and goes deep first; it is the basis of cycle detection, topological sorting and connected components. Both are O(V + E).
*Dijkstra vs A: which should I use?** They find the same shortest path when A’s heuristic is admissible. Use A when you search for one goal and have a cheap lower bound on the remaining distance (Manhattan or straight-line distance on maps). Use Dijkstra when you need distances to many nodes or have no useful heuristic.
Why does Dijkstra fail with negative edge weights? Dijkstra finalises the closest unfinished node, assuming nothing found later can make it closer. A negative edge breaks that assumption. Bellman-Ford handles negative weights by relaxing every edge repeatedly.
What is dynamic programming in simple terms?
Solve a problem by combining answers to smaller versions of it, and store each smaller answer so it is computed only once. Top-down DP is recursion plus a cache (functools.cache); bottom-up DP fills a table in an order where every dependency is ready.
Memoisation vs tabulation: which is better?
Memoisation (top-down) is easier to write from a recursive definition and only computes states you need. Tabulation (bottom-up) avoids recursion limits and often lets you keep only the last row or two, as in edit_distance.py.
How do I fix “RecursionError: maximum recursion depth exceeded”?
Rewrite the recursion with an explicit stack (as depth_first_search.py and strongly_connected_components.py do), switch top-down DP to bottom-up, or raise the limit with sys.setrecursionlimit for moderately deep inputs. Raising the limit too far can crash the interpreter, so an explicit stack is the robust fix.
Is binary search always O(log n)? On a random-access sorted sequence such as a Python list, yes. On a linked list, reaching the middle costs O(n), so binary search loses its advantage.
When should I use a Fenwick tree instead of a segment tree? When you need prefix or range sums with point updates: it is shorter and has smaller constants. Use a segment tree when the operation cannot be undone by subtraction, such as min, max or gcd.
How do I compute a modular inverse in Python?
If the modulus is prime, pow(a, p - 2, p) works by Fermat’s little theorem. In general, pow(a, -1, m) returns the inverse whenever gcd(a, m) == 1. extended_gcd in gcd_lcm.py shows how it works underneath.
Which algorithms should I learn first for coding interviews? Binary search, two pointers and sliding window, hash maps, BFS and DFS, heaps, sorting, basic dynamic programming, and union-find cover the majority of interview questions. The learning order marks the interview-critical steps.
Do I need to memorise these implementations? No. Aim to understand each invariant well enough to rebuild the code in a few minutes. Reading the docstring, closing the file and rewriting the function is the fastest way to get there.
Where to go next
Every link below was checked when this page was last reviewed.
Python documentation
- Sorting Techniques (Python HOWTO):
keyfunctions, stability and multi-key sorts. heapq,bisect,collections,functoolsandgraphlib: the standard-library versions of many algorithms in this repo.- TimeComplexity (Python wiki): the cost of list, dict, set and deque operations in CPython.
See algorithms move
- VisuAlgo: animated sorting, graph, tree and DP algorithms.
- Data Structure Visualizations (University of San Francisco): step-through animations of heaps, trees, hashing and graph algorithms.
- Python Tutor: paste any file from this repo and watch the variables and pointers change line by line.
Free courses and books
- MIT 6.006 Introduction to Algorithms (Spring 2020, MIT OpenCourseWare): lectures, notes and problem sets.
- Algorithms by Jeff Erickson: a free textbook with excellent chapters on recursion, DP and graphs.
- Open Data Structures: a free book on data structure implementation and analysis.
- Algorithms, 4th Edition (Sedgewick and Wayne) book site: lecture slides and Java code for a classic textbook.
- Competitive Programmer’s Handbook (PDF): a free, concise book covering most algorithms here and more.
Deeper references
- CP-Algorithms: detailed articles on string algorithms, number theory, Fenwick and segment trees, and graph algorithms.
- USACO Guide: a structured path from beginner to advanced competitive programming.
- Big-O Cheat Sheet: a compact poster of common complexities.
- Rosetta Code: the same tasks solved in hundreds of languages, useful for comparing approaches.
Practice
- CSES Problem Set: about 300 classic problems ordered by topic.
- Exercism Python track: small exercises with mentoring.
- Kattis, AtCoder and HackerRank: problem archives and contests that accept Python.
- Tech Interview Handbook and its Grind 75 list: interview preparation guides and a curated question schedule.
- NeetCode roadmap: interview problems grouped by topic, with video explanations.
Contributing
Pull requests are welcome. Please keep entries accurate and in the same spirit:
- One algorithm per file, standard library only, with a docstring covering the idea, complexity and when to use it.
- Add tests in the matching
tests/test_<folder>.py, including edge cases, and make surepytestpasses. - Prefer clarity over cleverness. If a line needs a comment to be understood, consider rewriting it first.
- Double-check complexity claims and links; corrections to explanations are as valuable as new code.
License
Code and text are released under the MIT License.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.