Part 17 / Stage 4
Data structures and algorithms in Python
Goal: Learn the handful of data structures and patterns that solve most coding problems, measure their speed instead of guessing it, and build the habit of recognising which pattern a new problem needs. Time: ~12 hours of lessons — one or two sections a day (30–60 minutes), plus daily problem practice, across the stage's two weeks
What you will learn
In this exact order, because each topic leans on the one before it:
- Big-O notation - how to describe and measure "how slow" code gets as input grows
- Arrays and strings - what
listandstrreally cost, and 2D grids - Hashing -
dictandset, average O(1) lookup - Prefix sums and difference arrays - range totals in O(1)
- Two pointers and sliding window - scanning once instead of nesting loops
- Stack and queue with
collections.deque, plus the monotonic stack - Sorting, and what Python's
sorted()really does - Binary search, with
bisect- including binary search on the answer - Linked lists
- Recursion, divide and conquer, and backtracking
- Trees and binary search trees
- Heaps, with
heapq - Greedy algorithms - and how to spot a wrong one
- Intervals - merge, insert, and the sweep
- Tries - the autocomplete tree
- Graphs, with BFS and DFS
- Topological sort and union-find
- Shortest paths - Dijkstra
- Dynamic programming - state, transition, base case, order
- Bit manipulation - masks, shifts and XOR
A short closing section lists advanced extensions (KMP, Bellman-Ford, Fenwick/segment trees, math tricks) worth knowing OF now and learning properly later.
💡 This part leans heavily on Part 14: Python internals - especially its lessons on measuring speed (
timeit,time.perf_counter) and choosing the right data structure. If a Big-O claim here feels unfamiliar, that part explains the why underneath it.
🎯 Each numbered section ends with a Practice on LeetCode block: a visible "start here" list (88 problems across the twenty patterns - roughly this stage's "2-3 problems a day" for its two weeks), then a folded full list of core and stretch problems - 336 in total - for the daily practice that continues after. Every list and table runs from gentler to tougher, and the links point to LeetCode problems by name (a free account is enough; each linked problem was checked against LeetCode's own problem index, and none of them need a paid account). And don't forget the practice that needs no account at all: every code example on this page can be edited and run right here with its Run and Practice buttons, and the exercises at the end have a workbench beside them.
Topics in this part
Practice
Python workbench — write and run code here
Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.
Each topic above carries its own exercise and solution — open a topic and scroll to its exercise. All 20 exercises are also counted on the Python Practice page.
Advanced extensions (read later)
Everything above is the working toolkit. Four families show up in harder interviews and competitive programming; know what they are FOR now, learn them when a problem actually demands them — each is a focused afternoon once the twenty topics feel comfortable.
String matching: KMP, Z-algorithm, rolling hash. Finding a pattern inside a text without re-comparing from scratch after every mismatch. Python's text.find(pattern) already uses a fast search, which is why these matter more for understanding (and for interviews that ask "how would find() work?") than for everyday code. Rolling hashes also power plagiarism checkers and chunked file sync.
Negative and all-pairs shortest paths: Bellman–Ford, Floyd–Warshall. Dijkstra's nonnegative-weights rule is sometimes broken for real (currency arbitrage, score penalties). Bellman–Ford handles negative edges and detects negative cycles in O(V·E); Floyd–Warshall fills the full every-node-to-every-node distance table in O(V³) — tiny graphs only, but three nested loops you can write from memory.
Range-query trees: Fenwick (BIT) and segment trees. The prefix-sum section's arrays answer range questions on FROZEN data; these structures keep answering in O(log n) while the data keeps changing (a live leaderboard, an order book). A Fenwick tree is ~15 lines once you trust its bit trick; a segment tree is bigger but handles min/max/custom merges, not just sums.
Math toolkit: GCD/LCM, prime sieve, modular arithmetic. math.gcd, the sieve of Eratosthenes for all primes below n in O(n log log n), and the habit of taking every intermediate result % (10**9 + 7) when a problem says "answer modulo 1e9+7" (Python's ints never overflow, but the answer they ask for is the reduced one, and reducing as you go keeps numbers small and fast).
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Guessing Big-O instead of measuring | Intuition about "fast enough" is often wrong, especially as data grows | Time it with time.perf_counter/timeit, the way the Big-O topic and Part 14 do |
x in some_list inside a loop, on a growing list |
Each check is O(n), so the whole loop becomes O(n²) | Build a set/dict once, then check against that |
Using a list as a FIFO queue (list.pop(0)) |
O(n) per removal: every remaining item shifts | collections.deque and its O(1) popleft/appendleft |
Binary search or bisect on unsorted data |
Gives a confident, meaningless answer, no error raised | Sort first, or keep the structure sorted as you insert (bisect.insort) |
Forgetting a linked list's base case while relinking .next |
Silently drops the rest of the chain | Save node.next in a temporary variable before overwriting it |
| Inserting pre-sorted data into a BST one at a time | Builds a straight line, not a tree: O(n), not O(log n) | Shuffle the insert order, or use a different structure if order is fixed |
Treating heapq as a max-heap |
It is a MIN-heap: the smallest item pops first | Push negated numbers, or use heapq.nlargest |
| Recursing on overlapping subproblems without memoising | Quietly becomes exponential (naive Fibonacci, naive knapsack) | functools.cache, or build a bottom-up table |
| Backtracking without undoing a choice | Later branches inherit earlier, wrong state | Always pair every "choose" with an "un-choose" right after the recursive call |
| Re-summing a range inside a loop | O(n) per question quietly becomes O(n²) overall | Build a prefix-sum array once; each range becomes one subtraction |
| Trusting a greedy that passed three tests | Locally best is not always globally best — coins (1, 3, 4) against 6 | Say why the choice can never hurt, or hunt for the counterexample |
| Running Dijkstra over negative weights | Its "cheapest popped is final" promise breaks; answers go silently wrong | Nonnegative weights only — reach for Bellman–Ford otherwise |
Quick recap
- Big-O describes how work grows, not an exact time; measure with
time.perf_counter/timeitbefore trusting a guess. - A
listis a dynamic array: O(1) at the end, O(n) at the front; slices copy; build strings withjoin, not+=. dict/setgive average O(1) lookup via hashing; reach for them the moment "have I seen this?" shows up in a loop.- Prefix sums answer any range total in O(1) after one O(n) build; difference arrays batch range updates the same way.
- Two pointers and sliding windows turn an O(n²) nested loop into a single O(n) pass.
listis a fine stack;collections.dequeis the right queue - O(1) at both ends, unlikelist.pop(0); a monotonic stack answers "next greater" questions in O(n).- Recursion solves a smaller copy of the same problem; backtracking tries a choice, recurses, then undoes it.
sorted()/list.sort()is Timsort: O(n log n), stable; many patterns (binary search, interval merging) need sorted data first.- Binary search and
bisectneed sorted data and give O(log n), including "binary search on the answer." - Linked lists give O(1) insert/delete once you are at a node, at the cost of O(n) access by position.
- A balanced BST gives O(log n) search/insert/delete; traversals (in-order, level-order with a
deque) are O(n). heapqis a min-heap: O(log n) push/pop, O(1) peek - the engine behind "top-k" and priority queues.- A greedy choice needs a proof it can never hurt — or a counterexample will find it; (1, 3, 4) against 6 is the classic.
- Interval problems sort first, then sweep once; the peak of the sweep is "rooms needed".
- A trie makes lookup cost the word's length, not the dictionary's size — the autocomplete structure.
- BFS (fewest edges, with a
deque) and DFS (reachability) are both O(V + E). - Topological sort (Kahn's) orders directed acyclic prerequisites and exposes cycles; union-find counts groups without walking the graph.
- Dijkstra (
heapq, nonnegative weights) finds the cheapest path where BFS's fewest-hops answer is wrong. - Dynamic programming reuses answers to overlapping subproblems (
functools.cache, or a bottom-up table); name the state, transition, base case and order and the code writes itself. - Bits:
|=sets a flag,&= ~clears it,&tests it; XOR cancels pairs.
Checklist
- I can measure an algorithm's growth with
time.perf_counterinstead of guessing its Big-O. - I can replace an
in-on-a-list check inside a loop with aset/dict. - I can explain why list front-inserts are O(n), and build a string with
joininstead of+=. - I can build a prefix-sum array and answer any range total with one subtraction.
- I can solve a pair-sum or best-window problem with two pointers/sliding window instead of nested loops.
- I can build an undo stack and a FIFO queue, and explain why
dequebeatslist.pop(0). - I can write a backtracking function that chooses, recurses, and undoes its choice.
- I can sort by a custom multi-field key and merge overlapping intervals.
- I can use
bisectto search or insert into sorted data in O(log n). - I can build a singly linked list, reverse it, and detect a cycle with fast/slow pointers.
- I can build a BST, traverse it in-order and level-order, and explain when it degrades to O(n).
- I can keep a top-k list with
heapqand explain why it beats sorting everything. - I can run BFS on a small graph and explain when its fewest-hops answer is not the best route.
- I can spot a wrong greedy with a counterexample, and say out loud why a right one is safe.
- I can merge intervals and count how many rooms a day of meetings needs.
- I can build a trie and autocomplete a prefix from it.
- I can produce a valid prerequisite order with Kahn's algorithm, and detect when none exists.
- I can run Dijkstra on a small weighted graph and say why it needs nonnegative weights.
- I can set, clear and test bit flags, and find the unpaired number with XOR.
- I can memoise a slow recursive function with
functools.cacheand explain the speed-up. - I have solved at least 50 practice problems across these twenty patterns.