DSA Reset — The Coding Bar, Pattern by Pattern, in Python
"You do not have to invent the algorithm. You have to recognise which one it is, and then not make a mistake writing it."
01 · The hookFour Weeks, Two Coding Rounds, Nine Years Away From Puzzles
A coding round tests whether you can recognise a problem and use a known tool for it. It is not a test of cleverness. This page rebuilds that recognition in four weeks, one pattern at a time, in Python.
"Hi Priya, great news: Lumen Labs would like to move you to the full loop for the AI Engineer role. Four rounds, all in the week of 25 November. Round two is a classic 45-minute coding round on a shared editor: one medium problem, you talk while you code. Round three is an AI-assisted coding round: you get a small codebase and an AI assistant, and we watch how you drive it. Please confirm by Friday."
Priya Nair has nine years of experience. She has shipped payment services, migrated a monolith and run an on-call rota. She has not written a binary search since university. Last month she tried a practice problem and froze for twenty minutes, staring at an empty editor. The loop is in four weeks.
Her freeze had nothing to do with talent. She was trying to invent an algorithm. Interviewers do not expect that. They expect you to look at a problem, say which known pattern it is, and write it cleanly. Inventing is rare; recognising is the skill, and recognising can be trained.
This page is her four-week plan, written as a chapter. It runs in this order: how to measure speed (a few days of groundwork), the Python tools that do the heavy lifting, then twelve patterns, then the round itself. Each pattern is one short lesson: the words in a problem that give it away, a picture, a template, one problem built in small steps, and two for you to try.
You have used every one of these ideas at work without the names. A dict keyed by user id is hashing. A retry queue is a BFS. Pagination over a sorted index is a binary search. Deduplicating a feed is a set. The reset is mostly putting names on things you do already, then practising them under a clock.
Nothing here repeats other pages. For Python itself (lists, dicts, generators) see Appendix A1. For the full interview loop, the design round and the AI-enabled round at a high level, see Module 17. For working with an AI coder day to day, see Module 15. This page is only the coding bar.
"Why not just memorise 300 solutions?"
— Priya, on day one, after finding a list of 300 problems
Because the interviewer changes one detail and a memorised answer breaks. Two Sum becomes "return all pairs", or "the array is sorted", or "do it in constant memory". A memorised solution has no handle for that. A recognised pattern does: you know why it works, so you know what to change.
The honest downside: patterns alone do not finish the job. You still have to type correct code in 45 minutes, which only practice gives you. That is why every pattern below ends with problems for you to solve, not just to read.
02 · Weekend · Measuring speedBig-O in Plain Words, With a Stopwatch
Big-O is a way to say how the running time of a program grows as the input grows. Without it, you cannot tell whether your solution will finish in a second or in a week.
Priya opens the weekend by timing three tiny functions, because every interview answer ends with the question "what is the complexity?" and she wants a gut feeling, not a formula. Everything later (each pattern, each trade-off) is judged by how its time and memory grow, so the stopwatch comes first.
Big-O describes how work grows when the input size n grows. It ignores the machine, the language and small constants. It asks one question: if I make the input ten times bigger, roughly how much slower does this get?
A tiny example first. A loop over 1,000 items does about 1,000 steps; over 2,000 items, about 2,000: twice the work for twice the input. A loop inside a loop over 1,000 items does 1,000 × 1,000 = 1,000,000 steps; over 2,000 items, 4,000,000: four times the work for twice the input. Those two behaviours, "twice" and "four times", are the heart of Big-O. The table names the common ones.
| Name | Written | If n doubles | Typical source |
|---|---|---|---|
| Constant | O(1) | same time | dict lookup, list index |
| Logarithmic | O(log n) | one extra step | binary search, heap push |
| Linear | O(n) | twice as slow | one loop over the input |
| Linearithmic | O(n log n) | a little over twice | sorting |
| Quadratic | O(n²) | four times as slow | a loop inside a loop over the same data |
| Exponential | O(2ⁿ) | squared (!) | trying every subset or every path |
A table of words does not give you a feeling. A stopwatch does. We will build a small timing program in three chunks and run the three most common growth rates on the same data, then look at the result as a picture.
You are about to see timing code that uses time.perf_counter and a few small functions. You are not expected to know perf_counter yet: it is a stopwatch that counts in fractions of a second, and chunk 1 shows it alone.
Timing numbers below were measured on the author's machine. Yours will differ in the digits; the shape will be the same.
Build it in chunks
We build bigo_timing.py in three chunks. Each one runs on its own; the whole file comes after.
-
Chunk 1 — a stopwatch that times any function
Everything else needs a way to time a call, so this comes first. We run the function a few times and keep the fastest time, because the fastest run is the one least disturbed by other programs on the machine.
Step-by-step: what chunk 1 does, in plain English
stopwatch(fn, data, repeats=3)takes a function and its input.- It starts with
best = infinityso any real time is smaller. - Each repeat reads
time.perf_counter()before and after callingfn(data). minkeeps the fastest of the repeats; the result is multiplied by 1000 to give milliseconds.- The
if __name__ == "__main__":block runs only when you run the file directly, and times Python's built-insumon 100,000 numbers.
bigo_timing.py — chunk 1runs offlineimport json import random import time # ── chunk 1: a stopwatch ── def stopwatch(fn, data, repeats=3): """Run fn(data) a few times and keep the fastest time, in milliseconds. The fastest run is the least disturbed by other programs on the machine.""" best = float("inf") for _ in range(repeats): start = time.perf_counter() fn(data) best = min(best, time.perf_counter() - start) return best * 1000 if __name__ == "__main__": print(f"summing 100,000 numbers takes {stopwatch(sum, list(range(100_000))):.2f} ms")time.perf_counter()— a high-resolution stopwatch;if __name__ == "__main__":— code that runs only when the file is the main program.Run
python3 bigo_timing.py. The number will differ on your machine; it is the order of magnitude that matters.terminalactual output (this chunk adds)summing 100,000 numbers takes 0.55 ms -
Chunk 2 — three functions with three growth rates
Now we need something to time. Each function does a different amount of work for the same list, and the comments name the growth rate so you can check them against the table above.
Step-by-step: what chunk 2 does, in plain English
find_maxwalks the list once, keeping the biggest value seen: one pass, so O(n).sort_copyreturnssorted(nums), Python's built-in sort: O(n log n).has_duplicate_pairscompares every item with every later item using two nested loops: about n × n / 2 comparisons, so O(n²).- The inner loop starts at
i + 1so a pair is never compared twice and an item is never compared with itself. - Nothing prints in this chunk: it only adds functions.
bigo_timing.py — chunk 2runs offline# ── chunk 2: three functions with three different growth rates ── def find_max(nums): # looks at each number once: O(n) best = nums[0] for x in nums: if x > best: best = x return best def sort_copy(nums): # sorting: O(n log n) return sorted(nums) def has_duplicate_pairs(nums): # compares every pair: O(n^2) for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] == nums[j]: return True return Falsenested loops — each pass of the outer loop runs the whole inner loop;
range(i + 1, n)— start after the current index.Run
python3 bigo_timing.pywith chunks 1 to 2 in the file. Chunk 2 adds functions only, so the output is the same as chunk 1: the stopwatch line.terminalactual output (this chunk adds)summing 100,000 numbers takes 0.56 ms -
Chunk 3 — time all three at five sizes and print a table
The functions exist and the stopwatch exists. Chunk 3 joins them: it builds the same random list for each size, times each function, prints one row per size, and saves the numbers for the figure below.
Step-by-step: what chunk 3 does, in plain English
SIZESlists the five input sizes, doubling each time (250 up to 4,000), so growth is easy to see.random.seed(7)makes the "random" data the same on every run.random.sample(range(10 * n), n)picks n distinct numbers, sohas_duplicate_pairsnever finds a duplicate and always does its full worst-case work.- Each row stores the time for each function at that size.
- The main block prints the rows as a table and writes them to
bigo_timing.json.
bigo_timing.py — chunk 3runs offline# ── chunk 3: time them at growing sizes and print a table ── SIZES = [250, 500, 1000, 2000, 4000] def measure(): random.seed(7) rows = [] for n in SIZES: # distinct numbers, so has_duplicate_pairs never exits early data = random.sample(range(10 * n), n) rows.append({ "n": n, "O(n)": stopwatch(find_max, data), "O(n log n)": stopwatch(sort_copy, data), "O(n^2)": stopwatch(has_duplicate_pairs, data), }) return rows if __name__ == "__main__": rows = measure() print(f"{'n':>6} {'O(n) ms':>10} {'O(n log n) ms':>14} {'O(n^2) ms':>10}") for r in rows: print(f"{r['n']:>6} {r['O(n)']:>10.3f} {r['O(n log n)']:>14.3f} {r['O(n^2)']:>10.1f}") with open("bigo_timing.json", "w") as f: json.dump(rows, f)random.sample— pick distinct items; f-string format specs like{x:>10.3f}— right-align and show 3 decimals.Run
python3 bigo_timing.pywith chunks 1 to 3 in the file. A table with five rows appears. Look at how each column changes from one row to the next, not at the exact digits.terminalactual output (this chunk adds)summing 100,000 numbers takes 0.54 ms n O(n) ms O(n log n) ms O(n^2) ms 250 0.004 0.011 0.7 500 0.007 0.031 3.5 1000 0.012 0.076 14.4 2000 0.023 0.174 57.7 4000 0.044 0.379 231.8
The whole program
Lines 7–22 are chunk 1, 23–43 are chunk 2, 44–69 are chunk 3. Every chunk starts with a # ── chunk n ── comment. This file lives at code/a3-dsa-reset/bigo_timing.py, with its tests in test_patterns.py.
# Python 3.12, standard library only. Run: python3 bigo_timing.py
import json
import random
import time
# ── chunk 1: a stopwatch ──
def stopwatch(fn, data, repeats=3):
"""Run fn(data) a few times and keep the fastest time, in milliseconds.
The fastest run is the least disturbed by other programs on the machine."""
best = float("inf")
for _ in range(repeats):
start = time.perf_counter()
fn(data)
best = min(best, time.perf_counter() - start)
return best * 1000
if __name__ == "__main__":
print(f"summing 100,000 numbers takes {stopwatch(sum, list(range(100_000))):.2f} ms")
# ── chunk 2: three functions with three different growth rates ──
def find_max(nums): # looks at each number once: O(n)
best = nums[0]
for x in nums:
if x > best:
best = x
return best
def sort_copy(nums): # sorting: O(n log n)
return sorted(nums)
def has_duplicate_pairs(nums): # compares every pair: O(n^2)
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j]:
return True
return False
# ── chunk 3: time them at growing sizes and print a table ──
SIZES = [250, 500, 1000, 2000, 4000]
def measure():
random.seed(7)
rows = []
for n in SIZES:
# distinct numbers, so has_duplicate_pairs never exits early
data = random.sample(range(10 * n), n)
rows.append({
"n": n,
"O(n)": stopwatch(find_max, data),
"O(n log n)": stopwatch(sort_copy, data),
"O(n^2)": stopwatch(has_duplicate_pairs, data),
})
return rows
if __name__ == "__main__":
rows = measure()
print(f"{'n':>6} {'O(n) ms':>10} {'O(n log n) ms':>14} {'O(n^2) ms':>10}")
for r in rows:
print(f"{r['n']:>6} {r['O(n)']:>10.3f} {r['O(n log n)']:>14.3f} {r['O(n^2)']:>10.1f}")
with open("bigo_timing.json", "w") as f:
json.dump(rows, f)
summing 100,000 numbers takes 0.54 ms
n O(n) ms O(n log n) ms O(n^2) ms
250 0.004 0.011 0.7
500 0.007 0.031 3.5
1000 0.012 0.076 14.4
2000 0.023 0.174 57.7
4000 0.044 0.379 231.8
Read the output. Look down one column at a time. The O(n) column roughly doubles each row: 0.012, 0.023, 0.044 ms. The O(n log n) column a little more than doubles: 0.076, 0.174, 0.379. The O(n^2) column roughly quadruples: 14.4, 57.7, 231.8 ms. Doubling the input quadrupled the time. That is what O(n²) feels like.
bigo_timing.py: the same five sizes, three growth rates.- The red curve is the pair check that compares every item with every other. At n = 1,000 it took 14.4 ms; at n = 2,000, 57.7 ms; at n = 4,000, 232 ms. Doubling n made it about four times slower each time. That is what "quadratic" means in practice.
- The blue curve is
sorted(). At n = 4,000 it took 0.379 ms. Doubling n made it slightly more than twice slower (0.174 ms to 0.379 ms), the small extra being the log n factor. - The green curve is one scan with a running maximum: 0.044 ms at n = 4,000, and roughly double each time n doubles. On the left panel both cheap curves sit flat on the floor, which is why the right panel zooms in.
Now the picture, from the numbers you just printed: Fig. A3.1. In the left panel all three share one scale. The pair check (marker 1 in Fig. A3.1) climbs away and the other two lines are flat. The right panel zooms in so you can see the two cheap ones.
Extend the lines in your head to n = 1,000,000. The pair check would need about 500 billion comparisons. At the measured speed of roughly 34 million comparisons per second, that is about 4 hours, for something a set does in a fraction of a second. This is the gap an interviewer is probing when they say "can you do better?".
"My services handle millions of rows. Why does O(n²) on 4,000 items matter?"
— Priya, nine years of production behind her
Because in production the database does the hard part for you: it has indexes, so the quadratic part never runs in your code. A coding round takes the index away. You are the index. The interviewer is checking whether you know what the database was quietly doing for you all this time.
The honest limit: for small n, O(n²) is perfectly fine. A 20-item list does not need a heap. In a round you should say "n is small here, so the simple version is fine" when it is true. Choosing the simple solution on purpose is a senior signal, not a weak one.
Space matters too
Time is half of the answer. Space complexity is the extra memory your solution uses, not counting the input itself. The dict in Two Sum costs O(n) extra space to save a whole loop of time. This is the most common trade in the whole page: memory for speed. Always say both numbers out loud.
Before reading on: a program has a loop over n items, and inside it calls x in my_list on a Python list. What is the complexity?
Reveal the answer
O(n²). The inner in test scans the list, which is O(n), and it runs n times. Changing my_list to a set makes each test O(1) on average, and the whole loop O(n). This single swap is the most common fix in coding rounds.
The math behind Big-O and the n(n−1)/2 count — optional depth
Formal definition: f(n) = O(g(n)) means that for large enough n, f never exceeds some fixed multiple of g. We drop constants and smaller terms, so 3n² + 50n + 7 is O(n²): at n = 1,000 the first term is already 3,000,000 and the second is 50,000.
The pair count: the first item pairs with n − 1 others, the second with n − 2, and so on down to 0. The sum 1 + 2 + … + (n − 1) equals n(n − 1) / 2. For n = 4,000 that is 7,998,000.
Symbol key: f(n) the real number of steps; g(n) the simple shape we compare it with; n input size; O( ) "grows no faster than"; Σ is not needed here because the sum is the famous staircase 1 + 2 + … + (n − 1).
Quick reference — Big-O
- O(1) · O(log n) · O(n) · O(n log n) · O(n²)
- Same time · one extra step per doubling · twice · a bit over twice · four times when n doubles.
- Work out the complexity
- Count the loops that touch the input. Nested over the same data multiplies. One after another adds. Sorting adds n log n.
- Space complexity
- Extra memory beyond the input. The usual trade is O(n) memory (a dict or set) for a loop of time.
- Say both
- Always give time and space, and name the worst case.
- When small is fine
- If n ≤ about 1,000, an O(n²) answer is acceptable; say why you chose it.
03 · Weekend · Python's toolboxThe Built-In Toolkit and What Each Piece Costs
Python already contains the data structures that most interview solutions need. Knowing the cost of each operation is what lets you choose the right one in ten seconds.
Priya now knows how to measure growth. Her first practice problems failed for a boring reason: she kept writing loops where a dict, a set or a heap was already sitting in the standard library. Before any pattern, she lists what Python hands her for free, with the price of each operation, because every pattern below is built from these pieces.
Think of these as a drawer of tools. You do not need to build a hash table or a heap in a round; you need to pick the right one and know what it costs. The table below is the whole drawer.
| Tool | What it is | Fast operations | Slow operations (avoid in loops) | Reach for it when |
|---|---|---|---|---|
list | Ordered array | index, append, pop() at the end: O(1) | x in list, insert, pop(0), slicing: O(n) | You need order and positions |
dict | Key to value map (hash table) | get, set, delete, in: O(1) on average | looping all keys: O(n) | "Have I seen this?" and "what goes with this?" |
set | Unique values (hash table) | add, remove, in: O(1) on average | no order, no index | Duplicates, membership, visited marks |
collections.deque | Double-ended queue | append, appendleft, pop, popleft: O(1) | indexing in the middle: O(n) | BFS queues, sliding windows |
collections.Counter | Counts how many of each | build: O(n); lookup: O(1) | most_common() with no argument sorts: O(n log n) | Frequencies, anagram checks |
collections.defaultdict | dict with a default value | same as dict; no key checks | same as dict | Grouping: defaultdict(list) |
heapq | Min-heap on a plain list | heappush, heappop: O(log n); peek h[0]: O(1); heapify: O(n) | searching inside: O(n); only a min-heap (negate for a max-heap) | Top-k, smallest-so-far, merge k lists |
bisect | Binary search on a sorted list | bisect_left, bisect_right: O(log n) | insort is O(n) because inserting shifts items | Nearest value, insertion point |
sorted / list.sort | Stable sort | O(n log n) | sorting inside a loop | Sort first so neighbours matter |
The slow column is where most interview bugs live. Three of them deserve names, because each one hides a loop inside a single innocent line:
- Membership in a list.
if x in itemsscans the list. Inside a loop that makes O(n²). Use a set. - Popping from the front of a list.
items.pop(0)shifts every other item one place left. As a queue it is O(n²) overall. Use a deque. - Slicing as a copy.
items[1:]builds a whole new list. Recursing onitems[1:]copies n items at every level. Pass an index instead.
Two more facts about Python itself will save you in a round. Python's default recursion limit is 1,000 calls deep, so a recursive solution on a 100,000-long linked list crashes; say so, and convert to a loop. And a list used as a stack is fine: append and pop() at the end are both O(1).
toolkit_costs.py, drawn on a log scale (each tick is ten times the last).- The same 2,000 lookups cost 237 ms in a list and 0.05 ms in a set: about 4,700 times apart. A list must scan; a set jumps straight to the slot. This one gap is why "put it in a set" is the most common fix in coding rounds.
- Binary search over a sorted list (
bisect) took 0.37 ms: not as fast as a set, but it keeps order, so it can answer "what is the nearest value?" too. - Removing from the front 20,000 times took 21.7 ms for a list (every pop shifts all the items left) and 0.61 ms for a deque. Using a list as a queue is a quiet O(n²) bug.
Fig. A3.2 is the table above, measured. The first three bars are the same 2,000 lookups. A list needed 237 ms (marker 1). A set needed 0.05 ms. The last two bars are the pop-from-front trap (marker 3).
The program below uses a deque, a set and bisect without teaching them yet. Each gets a full lesson later. For now, run it and compare the numbers with the figure.
Step-by-step: what toolkit_costs.py does, in plain English
ms(fn)is a stopwatch: it runsfnthree times and returns the fastest time in milliseconds.itemsis a list of 20,000 numbers;as_setandas_dequehold the same numbers in other containers.targetsis the last 2,000 numbers: the worst case for a list scan, because each one sits near the end.- Three lines time 2,000 lookups:
t in items(scan),t in as_set(hash), andbisect.bisect_left(binary search on the sorted list). pop_front_listempties a list from the front 20,000 times;pop_front_dequedoes the same withpopleft.- Each result is printed with a note on the cost class.
# Python 3.12, standard library only. Run: python3 toolkit_costs.py
import bisect
import time
from collections import deque
def ms(fn, repeats=3):
best = float("inf")
for _ in range(repeats):
t = time.perf_counter()
fn()
best = min(best, time.perf_counter() - t)
return best * 1000
N = 20_000
items = list(range(N))
as_set = set(items)
as_deque = deque(items)
targets = list(range(N - 2000, N)) # worst case for a list scan: items near the end
print(f"{N:,} items, 2,000 lookups of items near the end")
print(f" x in list : {ms(lambda: [t in items for t in targets]):9.2f} ms (scans: O(n) each)")
print(f" x in set : {ms(lambda: [t in as_set for t in targets]):9.2f} ms (hash: O(1) each)")
print(f" bisect : {ms(lambda: [bisect.bisect_left(items, t) for t in targets]):9.2f} ms (sorted list: O(log n) each)")
def pop_front_list():
a = list(range(N))
while a:
a.pop(0)
def pop_front_deque():
d = deque(range(N))
while d:
d.popleft()
print(f"emptying {N:,} items from the front")
print(f" list.pop(0) : {ms(pop_front_list):9.2f} ms (shifts everything left: O(n) each)")
print(f" deque.popleft() : {ms(pop_front_deque):9.2f} ms (O(1) each)")
20,000 items, 2,000 lookups of items near the end
x in list : 236.81 ms (scans: O(n) each)
x in set : 0.05 ms (hash: O(1) each)
bisect : 0.37 ms (sorted list: O(log n) each)
emptying 20,000 items from the front
list.pop(0) : 21.70 ms (shifts everything left: O(n) each)
deque.popleft() : 0.61 ms (O(1) each)
Read the output. A set answered 2,000 lookups about 4,700 times faster than a list. The pop-from-front gap is smaller (about 35 times) but grows as n grows: at 200,000 items it would be about a hundred times larger in absolute time, since the list version is quadratic.
The stack, and why
Which language and which tools should you use for the coding rounds, given you have 45 minutes and no internet?
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| Language | Python 3.12 | Java, Go, C++, JavaScript/TypeScript | Shortest code to write, so the most time is left for thinking; dict, set, heapq, deque are built in. Weak spot: roughly 30 to 100 times slower than C++ on tight loops, and recursion depth stops at 1,000. | The role is a Java or Go shop and the interviewer asks for it (see the Java interview drill), or the problem statement has n around 107 or more and the time limit is tight. |
| Data structures | Built-ins only: list, dict, set, deque, heapq, bisect | sortedcontainers (SortedList), numpy | These are guaranteed to exist. sortedcontainers is a third-party package that interview editors usually do not have installed. | You must keep a sorted multiset under inserts and deletes with n above about 105 and the platform allows packages; otherwise say "insort is O(n) here, a balanced tree would be O(log n)". |
| Testing | pytest-style assert lines you write yourself | doctest, unittest, print statements | An assert line is the fastest way to test in a shared editor, and it fails loudly with the failing input. | The platform only reads standard output (HackerRank, CodeSignal): print the results and compare by eye. |
| Practice platform | LeetCode with a curated list such as the NeetCode roadmap | HackerRank, CodeSignal, Codeforces, AlgoExpert | Most question banks that interviewers draw from look like LeetCode problems, and a curated list keeps you from wandering. Weak spot: some problems on any platform are puzzles, not realistic. | Your target employer uses HackerRank or CodeSignal for the online assessment: do two timed sessions there in week 4 to learn the editor. |
| Timing | time.perf_counter and timed_round.py | timeit, cProfile, pytest-benchmark | No install, and the wall clock is the thing you are really fighting in a round. | You compare two versions that differ by under 1 ms: use timeit, which repeats the run for you. |
Use Python for the round, built-ins for the data structures, and bring your own asserts; switch language only when the job or the input size forces it.
Questions you might be asking now
The four questions below slow down the toolbox. Every answer uses the same table of step counts, shown once here, so you can check each number against it.
| n | n | n log₂ n | n(n−1)/2 |
|---|---|---|---|
| 8 | 8 | 24 | 28 |
| 1,000 | 1,000 | 9,965 | 499,500 |
| 1,000,000 | 1,000,000 | 19,931,568 | 499,999,500,000 |
What does O(n log n) really mean, and where does the "log" come from?
The log counts how many times you can halve n before reaching 1. Sorting splits the list in halves again and again, so there are about log₂ n levels of splitting, and each level touches all n items. n items times log n levels gives n log n.
Halving is easy to try by hand. Take n = 8 and keep halving:
- 8 → 4. One halving.
- 4 → 2. Two halvings.
- 2 → 1. Three halvings. So log₂ 8 = 3.
- 1,000. Halving 1,000 gives 500, 250, 125, 62, 31, 15, 7, 3, 1: nine halvings, and log₂ 1,000 = 9.97. So the log of a thousand is about 10.
- 1,000,000. About 20 halvings. A million items need only about twenty levels.
- Total work. Each level touches all n items, so 1,000 × about 10 = 9,965 steps, the middle cell of the table above.
- Starting from 8, three halvings reach 1 (8 → 4 → 2 → 1). So log₂ 8 = 3.
- Starting from 1,000 it takes nine halvings (each step drops the fraction, so 62 → 31 and so on). The exact log₂ 1,000 is 9.97, and we round it to "about 10".
- A million items still need only about 20 halvings. That slow growth is why sorting a million items costs about 20 million steps, not a trillion.
The honest limit: "log n" is a count of steps, not a time. It is the reason sorting 1,000,000 items (about 20 million steps) is thousands of times cheaper than comparing all pairs (about 500 billion).
log n is "how many times can I halve n"; it grows so slowly that 1,000,000 items only need about 20 levels.
Why is x in a_set fast, when x in a_list is slow?
A set does not search. It turns the value into a number (its hash) and jumps straight to the slot where that value would live. A list has no such jump, so it must look at items one by one.
Here is a simplified picture, using a set of four numbers and 8 slots. Real Python also handles collisions by probing nearby slots, but the idea is the same:
- Pick the slot. For small whole numbers the hash is the number itself, and the slot is the hash mod 8 (the remainder after dividing by 8). So 2 goes to slot 2, 7 to slot 7, 11 to slot 3 (11 − 8) and 15 to slot 7 (15 − 8).
- Handle the collision. 7 and 15 both want slot 7. Python moves one of them to a nearby free slot. This is rare when the table is mostly empty, which is why Python keeps tables well below full.
- Look up 11. Compute 11 mod 8 = 3, go to slot 3, find 11: one step.
- Look up 9. 9 mod 8 = 1, slot 1 is empty: not present, one step.
- Same lookup in a list. Compare against 2, then 7, then 11: three steps; for a missing value, all n steps.
- Each value is turned into a slot number, here by the remainder after dividing by 8. 2 goes to slot 2, 11 to slot 3 (11 − 8) and 7 to slot 7. No searching is needed to know where to look.
- 15 also wants slot 7. Python resolves collisions by trying another slot, which is rare while the table is mostly empty. This simplified picture does not show the exact probe order.
- A lookup is one slot check: 11 is found in slot 3 and 9 is proven absent by an empty slot 1. A list would compare against every item.
The measured result is in the figure: 237 ms for the list against 0.05 ms for the set, for the same 2,000 lookups. The downside: a set stores no order, and building it costs O(n) memory.
A set jumps to where the value must be; a list walks until it finds it.
Why is list.pop() fast but list.pop(0) slow?
A list is a row of boxes in memory. Removing the last box leaves the rest untouched. Removing the first box leaves a hole at the front, so every other item must shift one place left.
Take the list [a, b, c, d].
pop(). Remove d. Nothing else moves. One step.pop(0). Remove a. Then b moves to slot 0, c to slot 1, d to slot 2: three moves for a four-item list.- Empty the whole list from the front. The moves are 3 + 2 + 1 + 0 = 6 for four items. For 20,000 items the total is 20,000 × 19,999 / 2 = 199,990,000 item moves.
- Why only 21.7 ms? The shifting happens in fast C code, a block of memory copied at a time, so 200 million moves still finish quickly. At 200,000 items it would be 100 times more: about 2 seconds.
list.pop() and list.pop(0) do to the same four-item list.- Removing the last item leaves the others where they are: nothing moves.
- Removing the first item leaves a hole at the front, and every remaining item slides one place left. Three moves for a four-item list.
- Emptying a list from the front costs n × (n − 1) / 2 moves in all, so 199,990,000 for 20,000 items. It was quick in C code (21.7 ms) but grows with the square of n.
A deque is built differently: it stores items in linked blocks and tracks both ends, so popleft() never shifts anything. The price is that indexing into the middle is O(n).
Use a list as a stack (end only) and a deque as a queue (front and back).
Isn't 2n slower than n? Why does Big-O ignore the constant?
Yes, 2n really is twice as slow. Big-O ignores it because it compares shapes, and for large n the shape wins over any constant. A slow-but-straight line always beats a fast-but-curved one eventually.
Compare two made-up programs: A does 100 × n steps (a big constant, a straight line), B does n × n steps (a small constant, a curve).
- n = 50. A: 5,000 steps. B: 2,500 steps. B is faster.
- n = 100. A: 10,000. B: 10,000. They tie.
- n = 1,000. A: 100,000. B: 1,000,000. A is ten times faster.
- n = 1,000,000. A: 100,000,000. B: 1,000,000,000,000. A is ten thousand times faster.
The honest limit: below the crossover, the constant matters. That is why sorting a 10-item list with a simple loop can beat a fancy method. In a round, say "constants aside" and then, if time allows, mention one.
Big-O is the shape of the curve; the constant only decides who wins for small n.
The map: twelve patterns on one page
The toolbox is in the drawer, so Priya turns to the patterns. Before the first one, she wants the whole map: twelve cards, each with the words that give it away and the cost she should say out loud. She tapes it above her desk, and every section below is one card.
- Hashing is the starting point: a dict or set answers "have I seen this?" in one step. Many later patterns (prefix sums, sliding window) use a dict inside.
- Two pointers needs a reason to discard options, usually sorted order or symmetry; it uses no extra memory.
- Sliding window is for contiguous stretches with a rule. If the data has negatives, think prefix sums instead. The costs on each card are the ones to say out loud after naming the pattern.
Fig. A3.6 is the page to return to. Read the signal words on a card first, then the cost. Hashing (marker 1) and two pointers (marker 2) come first because later patterns reuse them. The drill near the end turns the same map into thirty practice questions.
Quick reference — The toolbox
- Fast for membership
setanddict: O(1) on average. Never a list.- Fast at both ends
deque. A list is only fast at the end.- Counting and grouping
Countercounts;defaultdict(list)groups.- Top-k, smallest first
heapq: push and pop O(log n), peek O(1). Min-heap only; negate for max.- Sorted data
bisectfinds a position in O(log n);sortedcosts O(n log n).- Hidden loops
in list,pop(0),insert(0, x), slicing, string+=in a loop.- Recursion depth
- Python stops at 1,000 calls by default.
04 · Week 1 · Pattern 1Hashing and Counting: "Have I Seen This Before?"
Hashing means storing what you have seen in a dict or set so that "have I seen this?" costs one step instead of a whole scan. Counting is the same idea with numbers attached.
Priya starts week one with the pattern she already uses daily, because a first win steadies a frozen mind. Her first practice problem, Two Sum, took her eight minutes with two nested loops and a bad feeling. The fix is one idea: stop searching, start remembering. This section builds that fix from the slow version up.
Signals: the words in the problem that point here
Read the problem statement for these clues. Any two of them together is usually enough to name the pattern:
- "Find two numbers that add up to…" or "find a pair with…"
- "Does it contain a duplicate?", "first repeated", "first unique"
- "How many times does each…", "most frequent", "count"
- "Group by…", "anagrams"
- The brute force is a loop inside a loop whose inner loop only asks "is it there?"
two_sum: ask the dict instead of scanning the array.- The current number is 7 (index 1). The partner it needs is the target minus itself: 9 − 7 = 2. Working out what you need, not what you have, is the whole trick.
- The dict holds every number seen so far and where. When the loop stood on 2 (index 0), it stored
2 → 0. Checking this dict costs one step, not a walk over the array. - The lookup succeeds, so the answer is the stored index 0 and the current index 1. The brute force would have needed up to n × (n − 1) / 2 pair checks to find the same thing.
Fig. A3.7 follows two_sum on [2, 7, 11, 15] with target 9. At the number 7 (marker 1), we do not scan the array for a 2. We ask the dict (marker 2), which already knows where the 2 is.
The move is to rephrase the question. "Which two numbers add up to 9?" is hard. "I am standing on 7; have I already met a 2?" is one dict lookup. Almost every hashing problem works by turning a pair question into a "have I met my partner" question.
The template: the shape to remember
Step-by-step: what the hashing template does, in plain English
first_repeatkeeps a set calledseen.- For each item, the line
if x in seenasks "have I met you before?" in one step. - If yes, return it. If not,
seen.add(x)remembers it for later. - If the loop ends, nothing repeated and the function returns
None.
# ── template: hashing ──
def first_repeat(items):
seen = set()
for x in items:
if x in seen: # "have I met you before?" is one O(1) question
return x
seen.add(x)
return None
The worked problem: Two Sum
Problem. Given a list of numbers and a target, return the indices of two different items that add up to the target. Example: [2, 7, 11, 15] with target 9 gives [0, 1].
We build it in three chunks: the brute force (so we have something correct to compare against), the dict version, and a random test that proves the fast version agrees with the slow one.
Build it in chunks
We build p01_hashing.py in three chunks. Each runs on its own; the whole file follows.
-
Chunk 1 — the brute force, so we have a correct answer to compare with
A slow correct version first. It gives us a reference for the tests, and it is also what you say out loud in the interview before you improve it.
Step-by-step: what chunk 1 does, in plain English
two_sum_slow(nums, target)tries every pair(i, j)withjafteri.- If the two values add up to
target, return their indices at once. - If no pair works, return an empty list.
- The main block runs it on the example.
p01_hashing.py — chunk 1runs offlinefrom collections import Counter, defaultdict # ── chunk 1: brute force - try every pair ── def two_sum_slow(nums, target): """Return the indices of two different items that add up to target.""" for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j] return [] if __name__ == "__main__": print(two_sum_slow([2, 7, 11, 15], 9))range(i + 1, len(nums))— pairs where j is always after i, so no pair is tried twice.Run
python3 p01_hashing.py. It finds the pair at indices 0 and 1.terminalactual output (this chunk adds)[0, 1] -
Chunk 2 — remember what you have seen in a dict
Chunk 1 asks "which earlier number is my partner?" by scanning. A dict answers that question in one step, so the inner loop disappears.
Step-by-step: what chunk 2 does, in plain English
seenmaps each value to the index where we saw it.enumerategives the index and the value together.need = target - xis the partner this number is looking for.- If
needis already inseen, we have a pair: return the stored index and the current one. - Otherwise store
xand its index. Storing after the check means a number can never pair with itself. - The main block also tries
[3, 3](two equal numbers, which must pair) and[1, 2]with target 99 (no answer).
p01_hashing.py — chunk 2runs offline# ── chunk 2: remember what you have seen in a dict ── def two_sum(nums, target): seen = {} # value -> index where we saw it for i, x in enumerate(nums): need = target - x # the partner this number is looking for if need in seen: return [seen[need], i] seen[x] = i # store AFTER checking, so a number never pairs with itself return [] if __name__ == "__main__": print(two_sum([2, 7, 11, 15], 9)) print(two_sum([3, 3], 6), two_sum([1, 2], 99))enumerate— index and item in one loop; a dict as memory.Run
python3 p01_hashing.pywith chunks 1 to 2 in the file. The same[0, 1]as the slow version, then[0, 1]for the twins and an empty list for no answer.terminalactual output (this chunk adds)[0, 1] [0, 1] [] -
Chunk 3 — prove the fast version agrees with the slow one on random inputs
A fast function that is wrong is worse than a slow one. The slow version is trusted, so we throw 500 random small inputs at both and compare them.
Step-by-step: what chunk 3 does, in plain English
random.seed(1)makes the "random" inputs the same every run, so a failure can be reproduced.- Each trial builds a short list of small numbers (empty lists included) and a random target.
- Several different answers can be right, so we compare only whether an answer exists.
- If the fast version returns a pair, check that the two indices differ and the values really add up.
- The main block runs the checker and prints how many inputs agreed.
p01_hashing.py — chunk 3runs offline# ── chunk 3: check the fast version against the slow one on random input ── def agree_on_random_inputs(trials=500): import random random.seed(1) for _ in range(trials): nums = [random.randint(-9, 9) for _ in range(random.randint(0, 8))] target = random.randint(-15, 15) slow, fast = two_sum_slow(nums, target), two_sum(nums, target) # several answers can be right, so compare existence, then check the fast answer is valid assert bool(slow) == bool(fast), (nums, target) if fast: assert fast[0] != fast[1] and nums[fast[0]] + nums[fast[1]] == target return trials if __name__ == "__main__": print("fast and slow agree on", agree_on_random_inputs(), "random inputs")randomised testing against a slow trusted version — a habit that finds edge cases you would not think of.
Run
python3 p01_hashing.pywith chunks 1 to 3 in the file. It prints that the two versions agree on 500 random inputs.terminalactual output (this chunk adds)fast and slow agree on 500 random inputs
The whole program
Lines 5–18 are chunk 1, 19–34 are chunk 2, 35–51 are chunk 3. Every chunk starts with a # ── chunk n ── comment. This file lives at code/a3-dsa-reset/p01_hashing.py, with its tests in test_patterns.py.
# Pattern 1 - hashing / counting. Python 3.12, standard library only.
from collections import Counter, defaultdict
# ── chunk 1: brute force - try every pair ──
def two_sum_slow(nums, target):
"""Return the indices of two different items that add up to target."""
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return []
if __name__ == "__main__":
print(two_sum_slow([2, 7, 11, 15], 9))
# ── chunk 2: remember what you have seen in a dict ──
def two_sum(nums, target):
seen = {} # value -> index where we saw it
for i, x in enumerate(nums):
need = target - x # the partner this number is looking for
if need in seen:
return [seen[need], i]
seen[x] = i # store AFTER checking, so a number never pairs with itself
return []
if __name__ == "__main__":
print(two_sum([2, 7, 11, 15], 9))
print(two_sum([3, 3], 6), two_sum([1, 2], 99))
# ── chunk 3: check the fast version against the slow one on random input ──
def agree_on_random_inputs(trials=500):
import random
random.seed(1)
for _ in range(trials):
nums = [random.randint(-9, 9) for _ in range(random.randint(0, 8))]
target = random.randint(-15, 15)
slow, fast = two_sum_slow(nums, target), two_sum(nums, target)
# several answers can be right, so compare existence, then check the fast answer is valid
assert bool(slow) == bool(fast), (nums, target)
if fast:
assert fast[0] != fast[1] and nums[fast[0]] + nums[fast[1]] == target
return trials
if __name__ == "__main__":
print("fast and slow agree on", agree_on_random_inputs(), "random inputs")
[0, 1]
[0, 1]
[0, 1] []
fast and slow agree on 500 random inputs
Read the output. The two versions agree on 500 inputs, including empty lists and repeated numbers. In an interview you would not run 500 random tests, but you would walk the dict version through [3, 3] by hand: first 3 is stored, second 3 finds it. That one example covers the most common bug.
Complexity, said out loud
Time: one pass, each step O(1) on average, so O(n). The brute force was O(n²). Space: the dict can hold n entries, so O(n). Say it as a trade: "I spend O(n) memory to remove the inner loop."
Be ready for the follow-up "what if the array is sorted?" The answer is two pointers, the next pattern, which needs no dict at all and so uses O(1) memory.
Your turn: two practice problems
Try each on paper or in an editor first, with a timer set to 15 minutes. The solutions are hidden; each has tests in test_patterns.py that pass.
Given a list of words, group the words that are made of the same letters. ["eat", "tea", "tan", "ate", "nat", "bat"] gives three groups.
Signal to look for: "group by" plus "same letters" means: find a key that is equal for all words in a group.
Show a solution, with its tests
Step-by-step: what group_anagrams does, in plain English
groupsis adefaultdict(list): a missing key starts as an empty list.- For each word, sort its letters to make a key. Anagrams share the same sorted letters.
- Append the word to the list for that key.
- Return all the lists.
# ── practice: group_anagrams ──
def group_anagrams(words):
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w) # same letters sorted = same key
return list(groups.values())
Time O(n × k log k) for n words of length k (the sort of each word); space O(n × k). If the words are only lowercase letters, a 26-count tuple as the key makes it O(n × k).
Given an unsorted list, return the length of the longest run of consecutive integers (like 1, 2, 3, 4). [100, 4, 200, 1, 3, 2] gives 4. Do it in O(n).
Signal to look for: "Unsorted" plus "O(n)" rules out sorting; membership checks need a set.
Show a solution, with its tests
Step-by-step: what longest_consecutive does, in plain English
- Put all numbers in a set so lookups are O(1).
- For each number, only start counting if
x - 1is not in the set: that makes x the beginning of a run. - From a beginning, keep checking
x + lengthand count how far the run goes. - Keep the longest run seen.
# ── practice: longest_consecutive ──
def longest_consecutive(nums):
s = set(nums)
best = 0
for x in s:
if x - 1 not in s: # only start counting at the beginning of a run
length = 1
while x + length in s:
length += 1
best = max(best, length)
return best
Time O(n): each number is stepped over at most twice, once by the outer loop and once while some run counts through it. Space O(n). The "start only at the beginning of a run" check is what stops the inner loop from rerunning on every number.
Quick reference — Hashing and counting
- The signal
- "Have I seen this?", "pair that adds to…", "duplicate", "count", "group".
- The tool
setfor membership,dictfor value to index,Counterfor counts,defaultdict(list)for groups.- The trick
- Work out what you need from the current item (target − x) and look that up.
- Cost
- Time O(n), space O(n).
- The trap
- Store after you check, or an item pairs with itself.
04 · Week 1 · Pattern 2Two Pointers: One Finger at Each End
Two pointers means walking through the data with two index variables, usually from both ends, so each step rules out a whole group of answers at once.
After Monday's win, Priya meets a problem where the dict is not enough: the data is sorted, or the answer is a stretch between two walls. Her instinct is another nested loop. The sorted order is a hint she has not learned to read yet: if the data is ordered, one finger at each end can discard many options in a single move.
Signals: the words in the problem that point here
Read the problem statement for these clues. Any two of them together is usually enough to name the pattern:
- "The array is sorted" plus "find a pair or a triple"
- "Palindrome", "reverse", "compare from both ends"
- "In place", "O(1) extra space", "remove duplicates", "move all zeroes"
- "Container", "area between two lines"
- The brute force tries every pair, and a sorted order or a symmetry suggests that most pairs are pointless
[1, 8, 6, 2, 5, 4, 8, 3, 7] at the moment the best area, 49, appears.- The left pointer stands on index 1 (height 8). It started at index 0 and moved right because height 1 was the shorter wall.
- The right pointer stands on index 8 (height 7). Water cannot rise above the shorter wall, so this pair holds 7 high.
- The dashed box is the water: width 8 − 1 = 7 times height min(8, 7) = 7, which is 49. The pointer on the shorter wall moves next, because moving the taller one only makes the box narrower with the same limit.
Fig. A3.8 shows [1, 8, 6, 2, 5, 4, 8, 3, 7], where each number is the height of a wall. Water between two walls rises only to the shorter one. At the moment drawn, the left pointer is on height 8 (marker 1) and the right on height 7 (marker 2), and the box holds 7 × 7 = 49.
Which pointer should move? The shorter wall is the limit. Keeping it and moving the other pointer inward only reduces the width, so the area cannot grow. Moving the shorter one is the only move that could help. That argument, "this option can never be better, so discard it", is what makes two pointers correct, and it is the sentence to say in the interview.
The template: the shape to remember
Step-by-step: what the two pointers template does, in plain English
pair_with_sum_sortedputsloat the first item andhiat the last.- It adds the two values and compares the total with the target.
- If equal, return the pair.
- If the total is too small, the only way to grow it is to move
loright (to a bigger value). - If too big, move
hileft. Each step discards one end for good, so the loop ends after at most n steps.
# ── template: two pointers ──
def pair_with_sum_sorted(nums, target):
lo, hi = 0, len(nums) - 1
while lo < hi:
total = nums[lo] + nums[hi]
if total == target:
return lo, hi
if total < target:
lo += 1 # too small: the left end must grow
else:
hi -= 1 # too big: the right end must shrink
return None
The worked problem: Container With Most Water
Problem. Given a list of wall heights, choose two walls that together with the floor hold the most water. The area is the distance between them times the shorter height. For [1, 8, 6, 2, 5, 4, 8, 3, 7] the answer is 49.
Build it in chunks
We build p02_two_pointers.py in three chunks, using the same brute-force-first habit.
-
Chunk 1 — the brute force: try every pair of walls
Same habit as Monday: a correct slow version first. It also lets us test the clever one.
Step-by-step: what chunk 1 does, in plain English
- Loop over every pair
(i, j)with j after i. - The area is the width
j - itimes the shorter height. - Keep the biggest area seen.
- The main block runs the example.
p02_two_pointers.py — chunk 1runs offline# ── chunk 1: brute force - try every pair of walls ── def max_water_slow(heights): """Two walls and the floor make a tank. Return the biggest area.""" best = 0 for i in range(len(heights)): for j in range(i + 1, len(heights)): best = max(best, (j - i) * min(heights[i], heights[j])) return best if __name__ == "__main__": print(max_water_slow([1, 8, 6, 2, 5, 4, 8, 3, 7]))min(a, b)— the shorter of two walls.Run
python3 p02_two_pointers.py. It prints 49.terminalactual output (this chunk adds)49 - Loop over every pair
-
Chunk 2 — start at both ends and move the shorter wall inward
The brute force checks n × n / 2 pairs. Two pointers throws away a wall at every step, so it needs at most n steps.
Step-by-step: what chunk 2 does, in plain English
leftandrightstart at the two ends.- The loop runs while the pointers have not met.
- Compute the area for the current pair and keep the best.
- Move the pointer sitting on the shorter wall inward: the other wall might be taller than something we have not seen yet, but the shorter wall can never do better with a smaller width.
- The main block prints the same example.
p02_two_pointers.py — chunk 2runs offline# ── chunk 2: start at both ends and move the shorter wall inward ── def max_water(heights): left, right = 0, len(heights) - 1 best = 0 while left < right: width = right - left best = max(best, width * min(heights[left], heights[right])) # the shorter wall limits the area; moving the taller one can only shrink it if heights[left] < heights[right]: left += 1 else: right -= 1 return best if __name__ == "__main__": print(max_water([1, 8, 6, 2, 5, 4, 8, 3, 7]))while left < right— two indexes moving towards each other.Run
python3 p02_two_pointers.pywith chunks 1 to 2 in the file. It prints 49 again, with no inner loop.terminalactual output (this chunk adds)49 -
Chunk 3 — prove the two versions agree on random inputs
The "move the shorter wall" argument is easy to get subtly wrong, so we check it against the brute force on 300 random lists.
Step-by-step: what chunk 3 does, in plain English
- Seed the random numbers so a failure can be repeated.
- Build a random short list, possibly empty, with heights from 0 to 9.
assertthe fast and slow areas are equal; a failure prints the list that broke it.- The main block prints how many inputs agreed.
p02_two_pointers.py — chunk 3runs offline# ── chunk 3: prove the fast version matches the slow one ── def agree(trials=300): import random random.seed(2) for _ in range(trials): h = [random.randint(0, 9) for _ in range(random.randint(0, 9))] assert max_water(h) == max_water_slow(h), h return trials if __name__ == "__main__": print("agree on", agree(), "random inputs")assert value, message— stops with a message if the check fails.Run
python3 p02_two_pointers.pywith chunks 1 to 3 in the file. It prints that the versions agree on 300 random inputs.terminalactual output (this chunk adds)agree on 300 random inputs
The whole program
Lines 4–17 are chunk 1, 18–36 are chunk 2, 37–48 are chunk 3. Every chunk starts with a # ── chunk n ── comment. This file lives at code/a3-dsa-reset/p02_two_pointers.py, with its tests in test_patterns.py.
# Pattern 2 - two pointers. Python 3.12, standard library only.
# ── chunk 1: brute force - try every pair of walls ──
def max_water_slow(heights):
"""Two walls and the floor make a tank. Return the biggest area."""
best = 0
for i in range(len(heights)):
for j in range(i + 1, len(heights)):
best = max(best, (j - i) * min(heights[i], heights[j]))
return best
if __name__ == "__main__":
print(max_water_slow([1, 8, 6, 2, 5, 4, 8, 3, 7]))
# ── chunk 2: start at both ends and move the shorter wall inward ──
def max_water(heights):
left, right = 0, len(heights) - 1
best = 0
while left < right:
width = right - left
best = max(best, width * min(heights[left], heights[right]))
# the shorter wall limits the area; moving the taller one can only shrink it
if heights[left] < heights[right]:
left += 1
else:
right -= 1
return best
if __name__ == "__main__":
print(max_water([1, 8, 6, 2, 5, 4, 8, 3, 7]))
# ── chunk 3: prove the fast version matches the slow one ──
def agree(trials=300):
import random
random.seed(2)
for _ in range(trials):
h = [random.randint(0, 9) for _ in range(random.randint(0, 9))]
assert max_water(h) == max_water_slow(h), h
return trials
if __name__ == "__main__":
print("agree on", agree(), "random inputs")
49
49
agree on 300 random inputs
Read the output. If the greedy argument were wrong, one of the 300 lists would eventually have raised an assertion error showing the exact list. In the interview, the same check is a hand trace of a short list such as [1, 1] (answer 1) and the empty list (answer 0).
Complexity, said out loud
Time: each loop step moves one pointer inward, so at most n steps in total: O(n). The brute force was O(n²). Space: O(1), just two integers and a best-so-far.
A related warning: two pointers needs a reason for each move. If you cannot say why the discarded options are worthless, you do not have the pattern yet; you have a guess.
Your turn: two practice problems
Try each on paper or in an editor first, with a timer set to 15 minutes. The solutions are hidden; each has tests in test_patterns.py that pass.
A string is a palindrome if it reads the same forwards and backwards once you ignore case and anything that is not a letter or a digit. "A man, a plan, a canal: Panama" is one. Return whether the string is.
Signal to look for: "Reads the same both ways" means compare from both ends towards the middle.
Show a solution, with its tests
Step-by-step: what is_palindrome does, in plain English
- Keep only letters and digits, lowercased, in a list.
- Start one index at each end.
- If the two characters differ, it is not a palindrome.
- Move both indices inward until they meet; if no mismatch, it is.
# ── practice: is_palindrome ──
def is_palindrome(s):
chars = [c.lower() for c in s if c.isalnum()]
i, j = 0, len(chars) - 1
while i < j:
if chars[i] != chars[j]:
return False
i += 1
j -= 1
return True
Time O(n), space O(n) for the filtered copy. You can reach O(1) space by skipping non-letters in place with the two pointers; mention it if asked.
Move all zeroes to the end of a list, keeping the other numbers in their order, in place and without a second list. [0, 1, 0, 3, 12] becomes [1, 3, 12, 0, 0].
Signal to look for: "In place" plus "keep the order" means a read pointer and a write pointer that both walk forward.
Show a solution, with its tests
Step-by-step: what move_zeroes does, in plain English
writemarks the slot where the next non-zero value belongs.readwalks through the whole list.- When
nums[read]is non-zero, swap it into thewriteslot and advancewrite. - Zeroes are left behind, pushed towards the end by the swaps.
# ── practice: move_zeroes ──
def move_zeroes(nums):
write = 0 # next slot for a non-zero value
for read in range(len(nums)):
if nums[read] != 0:
nums[write], nums[read] = nums[read], nums[write]
write += 1
return nums
Time O(n), one pass. Space O(1). This is the "fast and slow" form of two pointers: both move forwards, at different speeds.
Quick reference — Two pointers
- The signal
- Sorted data and a pair, or a symmetry (palindrome), or "in place".
- Converging form
- One pointer at each end, move the one that cannot be part of a better answer.
- Same-direction form
- A read pointer and a write pointer (move zeroes, dedupe).
- Cost
- Time O(n), space O(1).
- The justification
- Say why the discarded options cannot be better; that sentence is the proof.
04 · Week 1 · Pattern 3Sliding Window: A Stretch That Grows and Shrinks
A sliding window is a stretch of the data between a left edge and a right edge. You move the right edge forward to take in more, and the left edge forward to throw things out, and never move either edge back.
On Wednesday Priya meets her first real freeze: "the longest substring without repeating characters". Her brute force checks every substring, and she cannot see anything better. The clue is the word "substring": a continuous stretch. Continuous stretches with a rule that can break are the home of the sliding window, and its whole trick is that no letter is visited more than twice.
Signals: the words in the problem that point here
Read the problem statement for these clues. Any two of them together is usually enough to name the pattern:
- "Longest" or "shortest" substring or subarray
- "Contiguous" (the items must be next to each other)
- A rule that can be broken by adding an item: "no repeats", "at most k distinct", "sum at least S"
- "Maximum sum of k consecutive…" (a fixed-size window)
- The brute force checks every start and every end
a (index 3) arrives.- The left edge jumps from 0 to 1. It lands one past the earlier
a, so the old copy is outside the window. - The right edge is the loop variable; it moves one step on every turn and never goes back.
- The window now covers
b c a(indexes 1 to 3): three different letters, length 3, tying the best so far. The answer for the whole string is 3. - The dict is how the left edge knows where to jump without scanning: one lookup tells it where the earlier copy sat. The check "at or after left" matters, since a letter seen long ago outside the window must be ignored.
Fig. A3.9 freezes "abcabcbb" at the instant the second a arrives at index 3. The window was abc, and adding another a breaks the "no repeats" rule. The left edge jumps from 0 to 1 (marker 1), and the window becomes bca (marker 3).
Two kinds of windows exist. A fixed-size window has the same width all the time: add one item on the right, drop one on the left. A variable-size window grows until the rule breaks, then shrinks until it holds again. The variable form is the one that freezes people, so we study it.
The template: the shape to remember
Step-by-step: what the sliding window template does, in plain English
longest_window_at_most_k_distinctkeeps aCounterof what is inside the window.- Step 1: each loop turn takes in the new right item by counting it.
- Step 2: while the window has more than k distinct items, drop the left item (reduce its count, delete it at zero) and move
leftforward. - Step 3: once the rule holds again, record the width as a candidate best.
- Each item is added once and removed once, so the double loop is still O(n).
# ── template: sliding window ──
def longest_window_at_most_k_distinct(items, k):
counts = Counter()
left = best = 0
for right, x in enumerate(items):
counts[x] += 1 # 1. grow: take in the new right item
while len(counts) > k: # 2. shrink while the window breaks the rule
counts[items[left]] -= 1
if counts[items[left]] == 0:
del counts[items[left]]
left += 1
best = max(best, right - left + 1) # 3. record the best valid window
return best
The worked problem: Longest Substring Without Repeating Characters
Problem. Given a string, return the length of the longest substring that has no repeated character. "abcabcbb" gives 3 (abc); "bbbbb" gives 1; the empty string gives 0.
Before the variable window, the fixed one is worth seeing alone, because it uses the same "add one, drop one" idea without any rule to repair. Fig. A3.10 slides a window of size 3 over six numbers. The first window is summed in full (marker 1); every later one is the last total plus the number that entered minus the number that left (marker 2).
max_sum_window([2, 1, 5, 1, 3, 2], 3): four windows, each total made from the last by one add and one subtract.- The first window (2, 1, 5) is summed once, in full: 8. This is the only time we add k numbers.
- Every later total is the previous total plus the number that entered minus the number that left: 8 + 1 − 2 = 7, then 7 + 3 − 1 = 9, then 9 + 2 − 5 = 6. The best is 9. That update is why the loop is O(n), not O(n × k).
Build it in chunks
We build p03_sliding_window.py in three chunks.
-
Chunk 1 — the brute force: check every substring
A trustworthy slow version again. For each start and end we ask "are all letters different?" by comparing the length of the substring with the length of its set of letters.
Step-by-step: what chunk 1 does, in plain English
- Two loops choose a start
iand an endj. part = s[i:j + 1]is that substring.- If its set of letters is as long as the substring itself, there are no repeats.
- Keep the longest such length.
p03_sliding_window.py — chunk 1runs offline# ── chunk 1: brute force - check every substring ── def longest_unique_slow(s): """Length of the longest stretch of s with no repeated character.""" best = 0 for i in range(len(s)): for j in range(i, len(s)): part = s[i:j + 1] if len(set(part)) == len(part): best = max(best, len(part)) return best if __name__ == "__main__": print(longest_unique_slow("abcabcbb"))set(part)— the unique letters; its length equals the substring length only if nothing repeats.Run
python3 p03_sliding_window.py. It prints 3 for"abcabcbb".terminalactual output (this chunk adds)3 - Two loops choose a start
-
Chunk 2 — grow the right edge, and jump the left edge when the rule breaks
The brute force is O(n³): n² substrings, each checked in O(n). The window visits each letter once.
Step-by-step: what chunk 2 does, in plain English
last_seenmaps each letter to the latest index where it appeared.rightmoves forward one letter at a time (the loop).- If this letter is already inside the window (its last position is at or after
left), moveleftto one past that earlier position. - Record the letter's new position.
- The window is
left..right, so its width isright - left + 1; keep the best. - The main block tries three inputs, including the empty string.
p03_sliding_window.py — chunk 2runs offline# ── chunk 2: grow the right edge, shrink the left edge when the rule breaks ── def longest_unique(s): last_seen = {} # character -> index where we last saw it left = 0 best = 0 for right, ch in enumerate(s): if ch in last_seen and last_seen[ch] >= left: left = last_seen[ch] + 1 # jump the left edge past the earlier copy last_seen[ch] = right best = max(best, right - left + 1) return best if __name__ == "__main__": print(longest_unique("abcabcbb"), longest_unique("bbbbb"), longest_unique(""))A dict storing "last position" so the left edge can jump instead of crawl.
Run
python3 p03_sliding_window.pywith chunks 1 to 2 in the file. It prints 3 for the long example, then3 1 0for the three inputs.terminalactual output (this chunk adds)3 1 0 -
Chunk 3 — compare fast and slow on random strings
The condition "at or after left" is the classic mistake, so we let the slow version police it.
Step-by-step: what chunk 3 does, in plain English
- Seed the random numbers.
- Build random strings from just the letters a, b, c, so repeats are frequent and edge cases appear often.
- Assert both versions return the same length.
- The main block prints the number of strings that agreed.
p03_sliding_window.py — chunk 3runs offline# ── chunk 3: compare fast and slow ── def agree(trials=300): import random random.seed(3) for _ in range(trials): s = "".join(random.choice("abc") for _ in range(random.randint(0, 10))) assert longest_unique(s) == longest_unique_slow(s), s return trials if __name__ == "__main__": print("agree on", agree(), "random strings")Small alphabets in random tests — they force the tricky cases to appear.
Run
python3 p03_sliding_window.pywith chunks 1 to 3 in the file. It prints that both versions agree on 300 random strings.terminalactual output (this chunk adds)agree on 300 random strings
The whole program
Lines 4–19 are chunk 1, 20–36 are chunk 2, 37–48 are chunk 3. Every chunk starts with a # ── chunk n ── comment. This file lives at code/a3-dsa-reset/p03_sliding_window.py, with its tests in test_patterns.py.
# Pattern 3 - sliding window. Python 3.12, standard library only.
# ── chunk 1: brute force - check every substring ──
def longest_unique_slow(s):
"""Length of the longest stretch of s with no repeated character."""
best = 0
for i in range(len(s)):
for j in range(i, len(s)):
part = s[i:j + 1]
if len(set(part)) == len(part):
best = max(best, len(part))
return best
if __name__ == "__main__":
print(longest_unique_slow("abcabcbb"))
# ── chunk 2: grow the right edge, shrink the left edge when the rule breaks ──
def longest_unique(s):
last_seen = {} # character -> index where we last saw it
left = 0
best = 0
for right, ch in enumerate(s):
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1 # jump the left edge past the earlier copy
last_seen[ch] = right
best = max(best, right - left + 1)
return best
if __name__ == "__main__":
print(longest_unique("abcabcbb"), longest_unique("bbbbb"), longest_unique(""))
# ── chunk 3: compare fast and slow ──
def agree(trials=300):
import random
random.seed(3)
for _ in range(trials):
s = "".join(random.choice("abc") for _ in range(random.randint(0, 10)))
assert longest_unique(s) == longest_unique_slow(s), s
return trials
if __name__ == "__main__":
print("agree on", agree(), "random strings")
3
3 1 0
agree on 300 random strings
Read the output. A small alphabet is the point: strings like abba are likely among the 300. In abba, when the second a arrives, the earlier a is outside the window, so the left edge must not move backwards. The test file includes that exact input.
Complexity, said out loud
Time: the right edge moves n times and the left edge never moves backwards, so O(n). Both loops share one budget of 2n steps. Space: O(k) for k different characters (at most the alphabet size), which for lowercase letters is O(1).
Say the invariant: "the window always contains no repeats; on every step I either extend it or shrink it just enough to restore that." Interviewers listen for the invariant.
for right, ch in enumerate(s):1
if ch in last_seen and last_seen[ch] >= left:2
left = last_seen[ch] + 13
last_seen[ch] = right4
best = max(best, right - left + 1)5
- The loop variable is the right edge. It only moves forward, one step per turn. The mistake: writing a second loop to move it.
- The rule check. "Does the new character already sit inside the window?" The part after
andis the one people forget: a character seen long ago, outside the window, must not count. - The shrink. Jump the left edge to one past the earlier copy. The mistake: moving it back, or only one step at a time.
- Remember the position. Always update the dict, even when the shrink did not happen, so it holds the latest index.
- Measure the window. Width = right − left + 1; the
+ 1is because both ends are included. Forgetting it is the classic off-by-one.
Your turn: two practice problems
Try each on paper or in an editor first, with a timer set to 15 minutes. The solutions are hidden; each has tests in test_patterns.py that pass.
Given daily sales and a number k, find the largest total over any k consecutive days. [2, 1, 5, 1, 3, 2] with k = 3 gives 9.
Signal to look for: "k consecutive" is a fixed-size window: add the new item, drop the oldest.
Show a solution, with its tests
Step-by-step: what max_sum_window does, in plain English
- Sum the first k items to start the window.
- For each later item, add it and subtract the item that just left the window (k places behind).
- Keep the largest total.
# ── practice: max_sum_window ──
def max_sum_window(nums, k):
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k] # add the new item, drop the oldest
best = max(best, window)
return best
Time O(n), space O(1). The trick that makes it O(n) rather than O(n × k) is updating the total instead of re-adding k numbers every step.
Given positive numbers and a target, return the length of the shortest stretch whose sum is at least the target, or 0 if none. [2, 3, 1, 2, 4, 3] with target 7 gives 2 (the stretch 4 and 3).
Signal to look for: "Shortest stretch" with a sum rule that gets easier as you add items: grow the right edge, then shrink while it still holds.
Show a solution, with its tests
Step-by-step: what min_len_at_least does, in plain English
- Grow: add each number at the right edge to the running total.
- Shrink: while the total is at least the target, record the length, then drop the left number and move left.
- If no stretch ever qualified, return 0.
# ── practice: min_len_at_least ──
def min_len_at_least(nums, target):
left = total = 0
best = float("inf")
for right, x in enumerate(nums):
total += x
while total >= target: # shrink while the rule still holds
best = min(best, right - left + 1)
total -= nums[left]
left += 1
return 0 if best == float("inf") else best
Time O(n): each item enters once and leaves once. This version only works because every number is positive; with negatives, adding an item can make the total smaller and the shrink logic breaks. That is where prefix sums (next) take over.
Quick reference — Sliding window
- The signal
- "Longest/shortest substring or subarray", "contiguous", "at most k", a rule a new item can break.
- The loop
- Right edge advances every turn; left edge advances only to repair the rule; neither goes back.
- Fixed form
- Add the new item, subtract the oldest, update the total.
- Cost
- Time O(n), space O(k).
- The trap
- Test "inside the window" with a position check, and remember width = right − left + 1.
04 · Week 1 · Pattern 4Prefix Sums: Running Totals That Answer Range Questions
A prefix sum is a running total saved as you go. With it, the sum of any stretch is one subtraction, so you never re-add the same numbers twice.
Thursday begins with a problem that looks like Wednesday's: "how many subarrays add up to k?" Priya reaches for a sliding window and watches it fall apart, because the list contains negative numbers and adding an item no longer means the total only grows. The window needed a one-way rule. A running total with a memory does not need one, and that is today's pattern.
Signals: the words in the problem that point here
Read the problem statement for these clues. Any two of them together is usually enough to name the pattern:
- "Sum of a subarray", "range sum", "between index i and j"
- "How many subarrays add up to / equal k"
- "Many queries" on the same unchanging data
- Negative numbers (which break a sliding window)
- "Product of everything except itself"
[1, 2, 3, −3, 3]: each arc joins two totals that differ by k = 3.- Each arc joins an earlier prefix total and a later one. The prefix row is the running total after 0, 1, 2, … numbers, so it starts at 0 for "nothing taken yet". Each number in the bottom row sits between the two totals it separates.
- The bold arc joins the total 0 (before everything) and 3 (after the first two numbers). The difference is 3, so the numbers between them,
[1, 2], add up to 3. - Counting all arcs gives 5:
[1,2],[3],[1,2,3,−3],[3,−3,3]and the last[3]. The program never builds a subarray; it only asks "how many earlier totals equal running − k?".
Fig. A3.11 lists the running totals of [1, 2, 3, −3, 3]: 0, 1, 3, 6, 3, 6 (marker 1). The key fact: the sum of the numbers between two positions is the later total minus the earlier total. The bold arc (marker 2) joins totals 0 and 3, so the numbers between them, 1 and 2, add to 3.
To count subarrays that add up to k, count pairs of prefix totals that differ by exactly k. Walk the list keeping the running total, and at each step ask a dict "how many earlier totals equal running − k?". That is a hashing question, so this pattern is a prefix sum plus Monday's dict.
The template: the shape to remember
Step-by-step: what the prefix sums template does, in plain English
prefix_totalsstarts the list with 0 for "nothing taken yet".- Each next entry is the previous entry plus the next number.
- The result has one more entry than the input.
- The sum of
nums[i:j]isprefix[j] - prefix[i]: one subtraction, any range.
# ── template: prefix sums ──
def prefix_totals(nums):
prefix = [0] # prefix[i] = sum of the first i items
for x in nums:
prefix.append(prefix[-1] + x)
return prefix # sum of nums[i:j] = prefix[j] - prefix[i]
The worked problem: Subarray Sum Equals K
Problem. Given a list of integers (possibly negative) and a number k, count the contiguous subarrays whose sum is exactly k. [1, 2, 3, −3, 3] with k = 3 gives 5.
Build it in chunks
We build p04_prefix_sums.py in three chunks.
-
Chunk 1 — the brute force: add up every subarray
A slow, trusted count to compare with. It already avoids the worst waste by keeping a running total for each start, so it is O(n²), not O(n³).
Step-by-step: what chunk 1 does, in plain English
- For each start
i, set a runningtotalto 0. - Extend the end
jone item at a time, addingnums[j]. - Whenever the total equals k, count it.
- The main block runs the example.
p04_prefix_sums.py — chunk 1runs offlinefrom collections import defaultdict # ── chunk 1: brute force - add up every subarray ── def count_sum_k_slow(nums, k): """How many contiguous stretches of nums add up to exactly k?""" count = 0 for i in range(len(nums)): total = 0 for j in range(i, len(nums)): total += nums[j] if total == k: count += 1 return count if __name__ == "__main__": print(count_sum_k_slow([1, 2, 3, -3, 3], 3))A running total inside a loop.
Run
python3 p04_prefix_sums.py. It prints 5.terminalactual output (this chunk adds)5 - For each start
-
Chunk 2 — a running total plus a dict of the totals seen so far
The brute force re-adds the same numbers. The dict lets us ask "how many earlier prefixes make a subarray ending here equal to k?" in one step.
Step-by-step: what chunk 2 does, in plain English
seencounts how many times each prefix total has occurred; it starts with{0: 1}, the empty prefix, so subarrays starting at index 0 are counted.runningis the total so far.- For each number, add it to
running. - A subarray ending here adds to k if some earlier prefix equals
running - k; add that count to the answer. - Then record the current
runninginseen.
p04_prefix_sums.py — chunk 2runs offline# ── chunk 2: a running total plus a dict of totals seen so far ── def count_sum_k(nums, k): seen = defaultdict(int) seen[0] = 1 # the empty prefix: lets a stretch start at index 0 running = 0 count = 0 for x in nums: running += x # a stretch ending here adds to k if some earlier prefix equals running - k count += seen[running - k] seen[running] += 1 return count if __name__ == "__main__": print(count_sum_k([1, 2, 3, -3, 3], 3))defaultdict(int)— a dict whose missing keys start at 0, so noif key incheck is needed.Run
python3 p04_prefix_sums.pywith chunks 1 to 2 in the file. It prints 5 again, with one pass.terminalactual output (this chunk adds)5 -
Chunk 3 — compare fast and slow on random inputs with negatives
The easy-to-forget initial
{0: 1}only shows up on certain inputs; random tests find them.Step-by-step: what chunk 3 does, in plain English
- Seed the random numbers.
- Build short lists with numbers from −3 to 3 (zeros and negatives are the awkward cases).
- Pick a random k.
- Assert both counts match and print how many inputs agreed.
p04_prefix_sums.py — chunk 3runs offline# ── chunk 3: compare fast and slow ── def agree(trials=300): import random random.seed(4) for _ in range(trials): nums = [random.randint(-3, 3) for _ in range(random.randint(0, 9))] k = random.randint(-4, 4) assert count_sum_k(nums, k) == count_sum_k_slow(nums, k), (nums, k) return trials if __name__ == "__main__": print("agree on", agree(), "random inputs")Random inputs that include zero and negatives.
Run
python3 p04_prefix_sums.pywith chunks 1 to 3 in the file. It prints that both agree on 300 random inputs.terminalactual output (this chunk adds)agree on 300 random inputs
The whole program
Lines 5–21 are chunk 1, 22–39 are chunk 2, 40–52 are chunk 3. Every chunk starts with a # ── chunk n ── comment. This file lives at code/a3-dsa-reset/p04_prefix_sums.py, with its tests in test_patterns.py.
# Pattern 4 - prefix sums. Python 3.12, standard library only.
from collections import defaultdict
# ── chunk 1: brute force - add up every subarray ──
def count_sum_k_slow(nums, k):
"""How many contiguous stretches of nums add up to exactly k?"""
count = 0
for i in range(len(nums)):
total = 0
for j in range(i, len(nums)):
total += nums[j]
if total == k:
count += 1
return count
if __name__ == "__main__":
print(count_sum_k_slow([1, 2, 3, -3, 3], 3))
# ── chunk 2: a running total plus a dict of totals seen so far ──
def count_sum_k(nums, k):
seen = defaultdict(int)
seen[0] = 1 # the empty prefix: lets a stretch start at index 0
running = 0
count = 0
for x in nums:
running += x
# a stretch ending here adds to k if some earlier prefix equals running - k
count += seen[running - k]
seen[running] += 1
return count
if __name__ == "__main__":
print(count_sum_k([1, 2, 3, -3, 3], 3))
# ── chunk 3: compare fast and slow ──
def agree(trials=300):
import random
random.seed(4)
for _ in range(trials):
nums = [random.randint(-3, 3) for _ in range(random.randint(0, 9))]
k = random.randint(-4, 4)
assert count_sum_k(nums, k) == count_sum_k_slow(nums, k), (nums, k)
return trials
if __name__ == "__main__":
print("agree on", agree(), "random inputs")
5
5
agree on 300 random inputs
Read the output. Without the starting {0: 1}, the fast version would miss every subarray that begins at index 0, such as [1, 2] here, and the random test would catch it within a few trials. Tests like this are how you find the "almost right" bug before the interviewer does.
Complexity, said out loud
Time: one pass with O(1) dict work per item: O(n). Space: O(n) for the dict. The brute force was O(n²).
Say why the sliding window failed here: it needs "adding an item can only make the total bigger", which negative numbers break. The prefix-sum form has no such requirement.
Your turn: two practice problems
Try each on paper or in an editor first, with a timer set to 15 minutes. The solutions are hidden; each has tests in test_patterns.py that pass.
Build a class that is given a list once, then answers "sum of items from index i to index j" many times. Each query must be O(1).
Signal to look for: "Many queries" on the same data: pay once to precompute, then answer instantly.
Show a solution, with its tests
Step-by-step: what RangeSum does, in plain English
- The constructor builds the prefix list, starting with 0.
query(i, j)returnsprefix[j + 1] - prefix[i], the later total minus the earlier one.- Both ends are included, hence the
j + 1.
# ── practice: RangeSum ──
class RangeSum:
def __init__(self, nums):
self.prefix = [0]
for x in nums:
self.prefix.append(self.prefix[-1] + x)
def query(self, i, j): # sum of nums[i..j], both ends included
return self.prefix[j + 1] - self.prefix[i]
Build O(n), each query O(1), space O(n). If the list changes between queries you need a different structure (a Fenwick tree), which is beyond this page; say so and move on.
Given a list of numbers, return a list where each position holds the product of all the other numbers, without using division. [1, 2, 3, 4] gives [24, 12, 8, 6].
Signal to look for: A "prefix" of products from the left and another from the right: the same idea with multiplication.
Show a solution, with its tests
Step-by-step: what product_except_self does, in plain English
- First pass left to right:
out[i]becomes the product of everything to the left of i. - Second pass right to left: multiply into
out[i]the product of everything to the right of i. - Each position now holds left × right, which is everything except itself.
# ── practice: product_except_self ──
def product_except_self(nums):
n = len(nums)
out = [1] * n
left = 1
for i in range(n): # out[i] = product of everything left of i
out[i] = left
left *= nums[i]
right = 1
for i in range(n - 1, -1, -1): # multiply in the product of everything right of i
out[i] *= right
right *= nums[i]
return out
Time O(n), extra space O(1) beyond the output. Division would fail on zeroes, which is why interviewers forbid it.
Quick reference — Prefix sums
- The signal
- "Subarray sum", "range sum", "many queries", negatives in the data.
- The build
prefix[0] = 0, thenprefix[i + 1] = prefix[i] + nums[i].- The query
- Sum of
nums[i..j]=prefix[j + 1] − prefix[i]. - Count subarrays with sum k
- Dict of prefix totals seen; add
seen[running − k]at each step; start with{0: 1}. - Cost
- Time O(n), space O(n).
05 · Week 2 · Pattern 5Stacks and the Monotonic Stack: Last In, First Settled
A stack is a pile where you only touch the top. It fits any problem where the most recent unfinished thing must be dealt with first, such as matching brackets or finding the next bigger value.
Week two starts with the stack, and Priya recognises it from daily life: the call stack, the undo history, the browser back button. Her blind spot is the harder cousin, the "next greater element" problem. Her brute force looks ahead from every day. The monotonic stack avoids the looking-ahead by keeping a pile of days still waiting, and settling them in bulk.
Signals: the words in the problem that point here
Read the problem statement for these clues. Any two of them together is usually enough to name the pattern:
- "Matching brackets", "valid parentheses", "nested"
- "Undo", "most recent", "reverse order"
- "Next greater element", "next warmer day", "days until…"
- "Evaluate an expression" (operands wait on a stack)
- The brute force looks ahead from each item to find something bigger
[73, 74, 75, 71, 69, 72, 76, 73].- Day 5 is 72°. It is the new arrival, and the question is which waiting days it answers.
- The stack holds days still waiting for a warmer day. Their temperatures never rise from top to bottom, 69 on top, 71 below it, then 75: that is why it is called monotonic, and why the top is always the easiest day to settle.
- Day 5 beats 69° and 71°, so those two days are settled (waits of 1 and 2 days) and leave the stack. It does not beat 75°, so the popping stops. Each day is pushed once and popped once: O(n) in total.
Fig. A3.12 stops [73, 74, 75, 71, 69, 72, 76, 73] at day 5, where it is 72° (marker 1). The stack holds days 2, 3 and 4 (marker 2): days still waiting for a warmer day. Their temperatures go down from the bottom to the top.
Today is warmer than 69° and 71°, so both are settled in one go (marker 3). It is not warmer than 75°, so the popping stops. A stack that keeps its contents in order like this is called monotonic: the values never rise from bottom to top.
The template: the shape to remember
Step-by-step: what the monotonic stack template does, in plain English
next_greatermakes a result list filled with −1 ("no greater value").stackholds indices of items still waiting.- For each new item, while the item on top of the stack is smaller than it, pop that index: its answer is the new item.
- Push the new index. It waits for something bigger.
- Items still on the stack at the end never found anything bigger; they keep −1.
# ── template: monotonic stack ──
def next_greater(nums):
out = [-1] * len(nums)
stack = [] # indices whose answer is still unknown
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
out[stack.pop()] = x
stack.append(i)
return out
The worked problem: Daily Temperatures
Problem. Given a list of daily temperatures, return for each day how many days you must wait for a warmer one, or 0 if there is none. [73, 74, 75, 71, 69, 72, 76, 73] gives [1, 1, 4, 2, 1, 1, 0, 0].
First try the pencil exercise below. It plays the stack by hand on four days, before the chunks show it as code.
Build it in chunks
We build p05_stack.py in three chunks.
-
Chunk 1 — the brute force: look ahead from every day
From each day, scan the following days until one is warmer. It is correct and slow, which makes it the reference.
Step-by-step: what chunk 1 does, in plain English
outcollects one wait per day.- For each day
i,waitstarts at 0. - Scan the days after it; at the first warmer one, record the distance and stop with
break. - Append the wait and continue.
p05_stack.py — chunk 1runs offline# ── chunk 1: brute force - look ahead from every day ── def days_until_warmer_slow(temps): """For each day, how many days until a warmer one? 0 if never.""" out = [] for i in range(len(temps)): wait = 0 for j in range(i + 1, len(temps)): if temps[j] > temps[i]: wait = j - i break out.append(wait) return out if __name__ == "__main__": print(days_until_warmer_slow([73, 74, 75, 71, 69, 72, 76, 73]))break— leave the inner loop at once.Run
python3 p05_stack.py. It prints[1, 1, 4, 2, 1, 1, 0, 0].terminalactual output (this chunk adds)[1, 1, 4, 2, 1, 1, 0, 0] -
Chunk 2 — a stack of days still waiting for a warmer day
The brute force re-scans the same days again and again. The stack remembers which days are still waiting, so each day is pushed once and popped once.
Step-by-step: what chunk 2 does, in plain English
outstarts as all zeros: "no warmer day" is the default.waitingis the stack of indices.- For each day, while the top waiting day is colder than today, pop it and set its wait to the difference of the indices.
- Then push today.
- Days left on the stack at the end keep 0.
p05_stack.py — chunk 2runs offline# ── chunk 2: a stack of days still waiting for a warmer day ── def days_until_warmer(temps): out = [0] * len(temps) waiting = [] # indices of days with no warmer day found yet for i, t in enumerate(temps): # today is warmer than every waiting day on top of the stack: settle them while waiting and temps[waiting[-1]] < t: j = waiting.pop() out[j] = i - j waiting.append(i) return out if __name__ == "__main__": print(days_until_warmer([73, 74, 75, 71, 69, 72, 76, 73]))Using a plain
listas a stack:appendto push,pop()to pop,waiting[-1]to peek.Run
python3 p05_stack.pywith chunks 1 to 2 in the file. It prints the same list as the brute force, from a single pass.terminalactual output (this chunk adds)[1, 1, 4, 2, 1, 1, 0, 0] -
Chunk 3 — compare fast and slow on random lists
Ties (equal temperatures) are the usual bug: equal is not warmer. A narrow temperature range makes ties common.
Step-by-step: what chunk 3 does, in plain English
- Seed the random numbers.
- Build random lists with temperatures from 60 to 70, so many are equal.
- Assert both versions agree.
- The main block prints how many lists agreed.
p05_stack.py — chunk 3runs offline# ── chunk 3: compare fast and slow ── def agree(trials=300): import random random.seed(5) for _ in range(trials): t = [random.randint(60, 70) for _ in range(random.randint(0, 10))] assert days_until_warmer(t) == days_until_warmer_slow(t), t return trials if __name__ == "__main__": print("agree on", agree(), "random inputs")A narrow value range to force ties.
Run
python3 p05_stack.pywith chunks 1 to 3 in the file. It prints that both versions agree on 300 random inputs.terminalactual output (this chunk adds)agree on 300 random inputs
The whole program
Lines 4–21 are chunk 1, 22–38 are chunk 2, 39–50 are chunk 3. Every chunk starts with a # ── chunk n ── comment. This file lives at code/a3-dsa-reset/p05_stack.py, with its tests in test_patterns.py.
# Pattern 5 - stack and monotonic stack. Python 3.12, standard library only.
# ── chunk 1: brute force - look ahead from every day ──
def days_until_warmer_slow(temps):
"""For each day, how many days until a warmer one? 0 if never."""
out = []
for i in range(len(temps)):
wait = 0
for j in range(i + 1, len(temps)):
if temps[j] > temps[i]:
wait = j - i
break
out.append(wait)
return out
if __name__ == "__main__":
print(days_until_warmer_slow([73, 74, 75, 71, 69, 72, 76, 73]))
# ── chunk 2: a stack of days still waiting for a warmer day ──
def days_until_warmer(temps):
out = [0] * len(temps)
waiting = [] # indices of days with no warmer day found yet
for i, t in enumerate(temps):
# today is warmer than every waiting day on top of the stack: settle them
while waiting and temps[waiting[-1]] < t:
j = waiting.pop()
out[j] = i - j
waiting.append(i)
return out
if __name__ == "__main__":
print(days_until_warmer([73, 74, 75, 71, 69, 72, 76, 73]))
# ── chunk 3: compare fast and slow ──
def agree(trials=300):
import random
random.seed(5)
for _ in range(trials):
t = [random.randint(60, 70) for _ in range(random.randint(0, 10))]
assert days_until_warmer(t) == days_until_warmer_slow(t), t
return trials
if __name__ == "__main__":
print("agree on", agree(), "random inputs")
[1, 1, 4, 2, 1, 1, 0, 0]
[1, 1, 4, 2, 1, 1, 0, 0]
agree on 300 random inputs
Read the output. The stack version gives the same list as the brute force. The cost difference only appears at scale: with 100,000 days in decreasing order, the brute force would make about five billion comparisons; the stack makes 100,000 pushes.
Complexity, said out loud
Time: every day is pushed once and popped at most once, so 2n stack operations in total: O(n), even though there is a loop inside a loop. Space: O(n) for the stack in the worst case (a list of falling temperatures).
This is the hardest thing to explain about the monotonic stack, so rehearse the sentence: "the inner while loop looks like O(n²), but each item can only be popped once, so the total is O(n)."
The plain stack is the simplest case of the same idea, and the first one most interviews ask. Fig. A3.13 follows "{[()]}" character by character. Openers are pushed (marker 1); each closer pops the top and must match it (marker 2). The string is valid only if the stack is empty at the end.
"{[()]}"; the last column is empty, so the string is valid.- Each opener goes on the stack. After the first three characters the stack holds
{,[,(, with the most recent on top. - Each closer must match the top.
)pops(,]pops[,}pops{. If the top did not match, or the stack were empty, the string would be invalid. Leftover openers at the end are also invalid.
Your turn: two practice problems
Try each on paper or in an editor first, with a timer set to 15 minutes. The solutions are hidden; each has tests in test_patterns.py that pass.
A string holds only the characters ( ) [ ] { }. Return whether every opener is closed by the right closer in the right order. "{[()]}" is valid; "(]" is not.
Signal to look for: "Nested" and "most recent opener must close first".
Show a solution, with its tests
Step-by-step: what valid_parentheses does, in plain English
pairsmaps each closer to its opener.- For an opener, push it onto the stack.
- For a closer, pop the top and check it is the matching opener; an empty stack or a mismatch means invalid.
- At the end the stack must be empty, or some opener was never closed.
# ── practice: valid_parentheses ──
def valid_parentheses(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif not stack or stack.pop() != pairs[ch]:
return False
return not stack
Time O(n), space O(n). The two classic misses are a closer with an empty stack (")") and leftover openers ("(("); the tests cover both.
Design a stack with push, pop and get_min, where all three are O(1).
Signal to look for: The minimum can be remembered at the moment each item is pushed.
Show a solution, with its tests
Step-by-step: what MinStack does, in plain English
- Each stack entry is a pair: the value, and the smallest value at or below it.
pushcomputes the new smallest from the previous top and the new value.popremoves the top pair and returns its value.get_minjust reads the second half of the top pair.
# ── practice: MinStack ──
class MinStack:
def __init__(self):
self.items = [] # each entry is (value, smallest value at or below it)
def push(self, x):
smallest = x if not self.items else min(x, self.items[-1][1])
self.items.append((x, smallest))
def pop(self):
return self.items.pop()[0]
def get_min(self):
return self.items[-1][1]
All three operations are O(1); space is O(n), one extra number per item. The idea (store the answer with the item, so removal restores the old answer for free) comes back in many design problems.
Quick reference — Stacks
- The signal
- "Matching/nested", "most recent first", "next greater/smaller", "undo".
- Plain stack
- Push openers; on a closer, pop and compare.
- Monotonic stack
- While today beats the top, pop and settle the top; then push today.
- Cost
- Time O(n) (each item pushed once, popped once), space O(n).
- The trap
- Decide whether equal values count as "greater" before you write the comparison.
05 · Week 2 · Pattern 6Binary Search: Halve the Question, Not the Data
Binary search finds something in a sorted list by looking at the middle and discarding half. The same idea also solves "what is the smallest value that works?" even when no list exists.
Priya has written binary search twice in her career, both times by copying. Tuesday she learns the version that interviews actually use: not "find 7 in this list", but "what is the smallest ship capacity that delivers everything in D days?" There is no list in that sentence. The skill is spotting that the answers can be lined up, with "too small" on one side and "good enough" on the other.
Signals: the words in the problem that point here
Read the problem statement for these clues. Any two of them together is usually enough to name the pattern:
- "Sorted" and "find" (the classic form)
- "Smallest/largest value such that…" (binary search on the answer)
- "Minimise the maximum" or "maximise the minimum"
- "In O(log n)", or n is huge (109 or more) so you cannot loop over it
- A yes/no test that flips only once: false, false, false, true, true, true
[3, 6, 7, 11]; guard has 8 hours. The answer space is speeds 1 to 11.- The dashed line is the flip. Every speed to its left needs more than 8 hours (27, 15, 10); every speed to its right needs 8 or fewer. This one-way flip is what lets us binary search something that is not even stored in a list.
- Each probe tries the middle speed and keeps the half that still contains the flip. Probe 2 tries speed 3 (10 hours, too slow) so the whole left side up to 3 is thrown away at once.
- When lo and hi meet, that speed is the smallest one that works: 4. Four probes instead of eleven; for speeds up to a billion it would be about 30.
Fig. A3.14 shows the answer space for a puzzle. Koko can eat bananas from piles of 3, 6, 7 and 11, and must finish in 8 hours. Eating faster needs fewer hours, so the "hours needed" row falls. There is a flip: three speeds too slow, then every speed fast enough (marker 1).
That one-way flip is the only requirement. You do not need a list; you need a yes/no test that goes from "no" to "yes" and never back. The search probes the middle (marker 2) and throws away the half that cannot contain the flip. It found speed 4 in four probes (marker 3).
The template: the shape to remember
Step-by-step: what the binary search template does, in plain English
first_truetakes a rangelo..hiand a yes/no functionworks.- While the range has more than one value, test the middle.
- If the middle works, the answer is the middle or something smaller: set
hi = mid. - If not, the answer must be larger: set
lo = mid + 1. - When
loandhimeet, that value is the smallest that works. You must be surehiitself works, or the answer does not exist.
# ── template: binary search ──
def first_true(lo, hi, works):
"""Smallest value in [lo, hi] for which works(value) is True; works must flip False -> True once."""
while lo < hi:
mid = (lo + hi) // 2
if works(mid):
hi = mid
else:
lo = mid + 1
return lo
The worked problem: Koko Eating Bananas
Problem. Koko has piles of bananas and h hours. Each hour she picks one pile and eats up to k bananas from it (leftovers in that pile are wasted until the next hour). Return the smallest k that finishes within h hours. Piles [3, 6, 7, 11], 8 hours: the answer is 4.
We build it in three chunks: plain binary search first (so the mechanics are separate from the idea), then the yes/no question, then the search over the answer.
Chunk 1 below is plain binary search, and it is worth seeing as a picture first. Fig. A3.15 searches for 7 in [1, 3, 5, 7, 9, 11]. The first probe, at 5 (marker 1), rules out the left half; the second (marker 2) rules out two more; the third finds 7 (marker 3).
find_index([1, 3, 5, 7, 9, 11], 7): faded cells are already ruled out.- The first probe is the middle of all six: 5. Since 5 is less than 7, the whole left half (1, 3, 5) is ruled out in one move.
- The second probe sits at the middle of the remaining 7, 9, 11 and finds 9, which is too big, so 9 and 11 are ruled out.
- One cell is left and it is 7: found at index 3 after three probes. For a million items the search would take about 20 probes.
Build it in chunks
We build p06_binary_search.py in three chunks.
-
Chunk 1 — plain binary search on a sorted list
Learn the loop on the familiar problem first. Everything after is this same loop with a different question.
Step-by-step: what chunk 1 does, in plain English
loandhiare the first and last index still possible.- While the range is not empty (
lo <= hi), look at the middle. - If the middle is the target, return its index.
- If the middle is too small, the target can only be to the right:
lo = mid + 1. Otherwisehi = mid - 1. - If the range empties, the target is missing: return −1.
p06_binary_search.py — chunk 1runs offlineimport math # ── chunk 1: plain binary search on a sorted list ── def find_index(sorted_nums, target): lo, hi = 0, len(sorted_nums) - 1 while lo <= hi: mid = (lo + hi) // 2 if sorted_nums[mid] == target: return mid if sorted_nums[mid] < target: lo = mid + 1 # target can only be to the right else: hi = mid - 1 # target can only be to the left return -1 if __name__ == "__main__": print(find_index([1, 3, 5, 7, 9, 11], 7), find_index([1, 3, 5, 7, 9, 11], 4))//— whole-number division, giving a whole index.Run
python3 p06_binary_search.py. It prints3 -1: found at index 3, and 4 not found.terminalactual output (this chunk adds)3 -1 -
Chunk 2 — the yes/no question: how many hours does speed k need?
Binary search on the answer needs a test. This function turns "speed" into "hours needed", and we look at its shape before searching it.
Step-by-step: what chunk 2 does, in plain English
- Each pile takes
ceil(pile / speed)hours: partial hours count as whole hours. sumadds up the hours of all piles.- The main block prints hours needed for speeds 1 to 6 so we can see the pattern.
p06_binary_search.py — chunk 2runs offline# ── chunk 2: the question "is speed k fast enough?" ── def hours_needed(piles, speed): """Koko eats `speed` bananas per hour from one pile at a time.""" return sum(math.ceil(p / speed) for p in piles) if __name__ == "__main__": piles = [3, 6, 7, 11] print([(s, hours_needed(piles, s)) for s in (1, 2, 3, 4, 5, 6)])math.ceil— round up.Run
python3 p06_binary_search.pywith chunks 1 to 2 in the file. It prints speed and hours pairs; the hours fall as speed rises: 27, 15, 10, 8, 8, 6.terminalactual output (this chunk adds)[(1, 27), (2, 15), (3, 10), (4, 8), (5, 8), (6, 6)] - Each pile takes
-
Chunk 3 — binary search on the answer: the smallest speed that works
Chunk 2 showed the hours falling as speed rises, so "fast enough" flips from false to true once. Binary search finds the flip.
Step-by-step: what chunk 3 does, in plain English
- The answer is between speed 1 and the biggest pile, because that speed finishes in one hour per pile, which is always enough when there are at most h piles.
- While
lo < hi, test the middle speed. - If it finishes in time, the answer might be smaller:
hi = mid(keep mid, it works). - If not,
lo = mid + 1(mid is too slow). - When they meet, return it.
- The main block prints the answers for two examples.
p06_binary_search.py — chunk 3runs offline# ── chunk 3: binary search on the answer - find the smallest speed that works ── def min_speed(piles, hours): lo, hi = 1, max(piles) # speed max(piles) always finishes in len(piles) hours while lo < hi: mid = (lo + hi) // 2 if hours_needed(piles, mid) <= hours: hi = mid # mid works; maybe something smaller does too else: lo = mid + 1 # mid is too slow; the answer is bigger return lo if __name__ == "__main__": print(min_speed([3, 6, 7, 11], 8), min_speed([30, 11, 23, 4, 20], 5))hi = mid(notmid - 1) — because mid itself could be the answer.Run
python3 p06_binary_search.pywith chunks 1 to 3 in the file. It prints4 30: speed 4 for the first example and 30 for the second.terminalactual output (this chunk adds)4 30
The whole program
Lines 5–22 are chunk 1, 23–33 are chunk 2, 34–47 are chunk 3. Every chunk starts with a # ── chunk n ── comment. This file lives at code/a3-dsa-reset/p06_binary_search.py, with its tests in test_patterns.py.
# Pattern 6 - binary search, including binary search on the answer. Python 3.12.
import math
# ── chunk 1: plain binary search on a sorted list ──
def find_index(sorted_nums, target):
lo, hi = 0, len(sorted_nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if sorted_nums[mid] == target:
return mid
if sorted_nums[mid] < target:
lo = mid + 1 # target can only be to the right
else:
hi = mid - 1 # target can only be to the left
return -1
if __name__ == "__main__":
print(find_index([1, 3, 5, 7, 9, 11], 7), find_index([1, 3, 5, 7, 9, 11], 4))
# ── chunk 2: the question "is speed k fast enough?" ──
def hours_needed(piles, speed):
"""Koko eats `speed` bananas per hour from one pile at a time."""
return sum(math.ceil(p / speed) for p in piles)
if __name__ == "__main__":
piles = [3, 6, 7, 11]
print([(s, hours_needed(piles, s)) for s in (1, 2, 3, 4, 5, 6)])
# ── chunk 3: binary search on the answer - find the smallest speed that works ──
def min_speed(piles, hours):
lo, hi = 1, max(piles) # speed max(piles) always finishes in len(piles) hours
while lo < hi:
mid = (lo + hi) // 2
if hours_needed(piles, mid) <= hours:
hi = mid # mid works; maybe something smaller does too
else:
lo = mid + 1 # mid is too slow; the answer is bigger
return lo
if __name__ == "__main__":
print(min_speed([3, 6, 7, 11], 8), min_speed([30, 11, 23, 4, 20], 5))
3 -1
[(1, 27), (2, 15), (3, 10), (4, 8), (5, 8), (6, 6)]
4 30
Read the output. The two bold ideas to say aloud: "the hours needed never go up as speed goes up, so I can binary search the speed", and "I keep mid when it works, because it might be the smallest." Using mid - 1 there is the classic mistake that skips the answer.
Complexity, said out loud
Time: the speed range has size max(pile) so the search takes log₂(max pile) probes, and each probe costs O(n) to compute the hours: O(n log m) where m is the largest pile. For piles up to 109, that is about 30 probes. Space: O(1).
Python also ships plain binary search for sorted lists: bisect.bisect_left(a, x) returns the index where x would go. In a round, use it for the simple form and mention you could write it by hand.
Your turn: two practice problems
Try each on paper or in an editor first, with a timer set to 15 minutes. The solutions are hidden; each has tests in test_patterns.py that pass.
A sorted list of distinct numbers was rotated at an unknown point, for example [4, 5, 6, 7, 0, 1, 2]. Return the index of a target, or −1, in O(log n).
Signal to look for: "Sorted but rotated" and "O(log n)": one half is always still sorted; decide which, then check whether the target lies inside it.
Show a solution, with its tests
Step-by-step: what search_rotated does, in plain English
- Look at the middle; if it is the target, return it.
- If the left half (
lo..mid) is sorted (nums[lo] <= nums[mid]), check whether the target falls in it and keep that half, else keep the other. - Otherwise the right half is sorted; apply the same check there.
- Repeat until the range is empty.
# ── practice: search_rotated ──
def search_rotated(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[lo] <= nums[mid]: # the left half is sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # the right half is sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1
Time O(log n), space O(1). The trick is that at least one half is always plainly sorted, so you can always make a decision.
Return the integer part of the square root of a non-negative integer without using a library: int_sqrt(8) is 2.
Signal to look for: "Largest value such that value × value ≤ n" is a flip from true to false; search the answer.
Show a solution, with its tests
Step-by-step: what int_sqrt does, in plain English
- The answer lies between 0 and n.
- Take the upper middle (
(lo + hi + 1) // 2) so the loop always makes progress when we keeplo = mid. - If
mid * mid <= n, mid is a candidate:lo = mid. Otherwisehi = mid - 1. - When they meet, that is the largest value that works.
# ── practice: int_sqrt ──
def int_sqrt(n):
lo, hi = 0, n
while lo < hi:
mid = (lo + hi + 1) // 2 # round up so the loop always makes progress
if mid * mid <= n:
lo = mid
else:
hi = mid - 1
return lo
Time O(log n). This is the mirror of Koko: finding the largest value that works, so we round the middle up. Rounding the wrong way causes an infinite loop, a bug worth practising on purpose.
Quick reference — Binary search
- The signal
- "Sorted + find", "smallest/largest value such that…", n so large you cannot loop.
- Plain form
lo <= hi, move tomid ± 1, return −1 if the range empties.- On the answer
- A yes/no test that flips once;
lo < hi; keepmidwhen it works. - Cost
- Time O(log range × cost of one test), space O(1).
- The traps
mid - 1vsmid; infinite loops when rounding the middle the wrong way.
05 · Week 2 · Pattern 7Linked Lists: Rewiring Arrows Without Losing the Rest
A linked list is a chain of nodes, each holding a value and an arrow to the next one. Problems about it are about rewiring arrows in the right order, so nothing is lost.
Wednesday brings linked lists. Priya has not touched one since university, and the whole shape is unfamiliar: no indexes, no length, just a head and arrows. Interviewers like this pattern because it is hard to fake: one arrow rewired too early and the rest of the list vanishes. The skill is a tiny routine, "save next, then rewire", practised until it is automatic.
Signals: the words in the problem that point here
Read the problem statement for these clues. Any two of them together is usually enough to name the pattern:
- "Linked list", "node", "head",
.next - "Reverse", "merge two sorted lists", "remove the n-th from the end"
- "Cycle", "loop", "meeting point"
- "Middle of the list" in one pass
- "In place", "O(1) extra space" on a list of nodes
1 → 2 → 3 → 4: the state after two turns of the loop.- Node 1 now points to None: it is the new tail. Its old arrow to 2 was cut in the first turn.
- Node 2 points back at node 1 and is
prev: the head of the reversed part. Whatever the loop does next hangs off this node. curis node 3, whose arrow has not been flipped yet.nxtwas saved as node 4 before the flip, which is why the code savescur.nextfirst. Cut the arrow before saving it and the rest of the list is lost.
Fig. A3.16 shows 1 → 2 → 3 → 4 after two turns of the reversing loop. Node 1 already points to None (marker 1). Node 2 points back at node 1 and is called prev (marker 2). The loop is standing on node 3, called cur (marker 3).
Three names carry the whole pattern: prev (already finished), cur (being worked on) and nxt (saved before we touch anything). The rule is always "save nxt first". Cut the arrow first and the rest of the list is gone: nothing points at it any more.
The template: the shape to remember
Step-by-step: what the linked list template does, in plain English
walk_with_previousstarts withprevas None andcuras the head.- In each turn, first save
cur.nextinnxt, so nothing is lost when an arrow changes. - The comment marks where you would change
cur.nextor read the values. - Then step forward:
prevbecomescurandcurbecomesnxt. - When
curbecomes None the walk is over andprevis the last node.
# ── template: linked list ──
def walk_with_previous(head):
prev, cur = None, head
while cur:
nxt = cur.next # always save next before touching cur.next
# ... use prev / cur / nxt here ...
prev, cur = cur, nxt
return prev
The worked problem: Reverse a Linked List
Problem. Given the head of a singly linked list, reverse it in place and return the new head. 1 → 2 → 3 → 4 becomes 4 → 3 → 2 → 1.
Because linked lists need a node class and two helpers (build from a Python list, print as a Python list), chunk 1 only sets up those. You will reuse them in every list problem.
Build it in chunks
We build p07_linked_list.py in three chunks.
-
Chunk 1 — a node class and two helpers: build and print
Before reversing anything we need a way to make a list and see it. These two helpers are test scaffolding, written once.
Step-by-step: what chunk 1 does, in plain English
ListNodeholds a value and anextarrow (None means the end).buildwalks a Python list backwards, attaching each new node in front of the current head.to_listwalks from the head, collecting values until it runs off the end.- The main block builds
[1, 2, 3]and prints it back.
p07_linked_list.py — chunk 1runs offline# ── chunk 1: the node and two helpers to build and print a list ── class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def build(values): head = None for v in reversed(values): head = ListNode(v, head) return head def to_list(head): out = [] while head: out.append(head.val) head = head.next return out if __name__ == "__main__": print(to_list(build([1, 2, 3])))A small class; building a list from the back so each new node points at the chain built so far.
Run
python3 p07_linked_list.py. It prints[1, 2, 3].terminalactual output (this chunk adds)[1, 2, 3] -
Chunk 2 — reverse the list by flipping one arrow at a time
This is the "save next, then rewire" routine from the figure, written as a loop.
Step-by-step: what chunk 2 does, in plain English
prevstarts as None: the reversed part is empty.curis the node being worked on.- Save
cur.nextinnxtbefore changing anything. - Point
cur.nextatprev: the arrow now goes backwards. - Move both pointers forward.
- When
curis None,previs the new head; return it. - The main block reverses a four-node list and also the empty list.
p07_linked_list.py — chunk 2runs offline# ── chunk 2: reverse the list by flipping one arrow at a time ── def reverse_list(head): prev = None cur = head while cur: nxt = cur.next # 1. save the rest before we cut the link cur.next = prev # 2. flip this arrow backwards prev = cur # 3. step forward cur = nxt return prev # prev is the new head if __name__ == "__main__": print(to_list(reverse_list(build([1, 2, 3, 4]))), to_list(reverse_list(None)))Reassigning attributes (
cur.next = prev) rewires the structure; no new nodes are created.Run
python3 p07_linked_list.pywith chunks 1 to 2 in the file. It prints[4, 3, 2, 1] []: the reversed list and the empty list.terminalactual output (this chunk adds)[4, 3, 2, 1] [] -
Chunk 3 — the same walk with a fast and a slow pointer finds the middle
The second classic list trick: two pointers moving at different speeds. When the fast one reaches the end, the slow one is halfway.
Step-by-step: what chunk 3 does, in plain English
- Both pointers start at the head.
- While
fastandfast.nextexist, moveslowone step andfasttwo steps. - When the loop ends,
slowis at the middle (the second of two middles for an even-length list). - The main block prints the middle value of a five-node and a four-node list.
p07_linked_list.py — chunk 3runs offline# ── chunk 3: the same walk with a fast and a slow pointer finds the middle ── def middle(head): slow = fast = head while fast and fast.next: slow = slow.next # one step fast = fast.next.next # two steps: when fast ends, slow is halfway return slow if __name__ == "__main__": print(middle(build([1, 2, 3, 4, 5])).val, middle(build([1, 2, 3, 4])).val)Two pointers at different speeds: "fast and slow".
Run
python3 p07_linked_list.pywith chunks 1 to 3 in the file. It prints3 3: the middle of 1-2-3-4-5, and the second middle of 1-2-3-4.terminalactual output (this chunk adds)3 3
The whole program
Lines 4–29 are chunk 1, 30–45 are chunk 2, 46–56 are chunk 3. Every chunk starts with a # ── chunk n ── comment. This file lives at code/a3-dsa-reset/p07_linked_list.py, with its tests in test_patterns.py.
# Pattern 7 - linked list basics. Python 3.12, standard library only.
# ── chunk 1: the node and two helpers to build and print a list ──
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def build(values):
head = None
for v in reversed(values):
head = ListNode(v, head)
return head
def to_list(head):
out = []
while head:
out.append(head.val)
head = head.next
return out
if __name__ == "__main__":
print(to_list(build([1, 2, 3])))
# ── chunk 2: reverse the list by flipping one arrow at a time ──
def reverse_list(head):
prev = None
cur = head
while cur:
nxt = cur.next # 1. save the rest before we cut the link
cur.next = prev # 2. flip this arrow backwards
prev = cur # 3. step forward
cur = nxt
return prev # prev is the new head
if __name__ == "__main__":
print(to_list(reverse_list(build([1, 2, 3, 4]))), to_list(reverse_list(None)))
# ── chunk 3: the same walk with a fast and a slow pointer finds the middle ──
def middle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next # one step
fast = fast.next.next # two steps: when fast ends, slow is halfway
return slow
if __name__ == "__main__":
print(middle(build([1, 2, 3, 4, 5])).val, middle(build([1, 2, 3, 4])).val)
[1, 2, 3]
[4, 3, 2, 1] []
3 3
Read the output. The empty list reverses to an empty list; the test suite also checks a one-node list. Those two cases are where most linked-list answers crash, because the loop is entered with nothing (or one thing) to rewire.
Complexity, said out loud
Time: each node is visited once, so O(n). Space: O(1) extra for the loop version, because only three pointers are held. A recursive reversal is also O(n) time but O(n) stack space, and for a very long list it would hit Python's 1,000-call recursion limit, so say "I will write it iteratively."
When stuck on a list problem, draw three boxes and the arrows on paper and move your finger as the code runs. Interviewers expect it.
Merging two sorted lists is the same rewiring routine with a helper node. Fig. A3.17 merges 1 → 3 → 5 with 2 → 4. List a (marker 1) and list b (marker 2) feed a result chain that starts at a dummy node (marker 3).
merge_sorted on 1 → 3 → 5 and 2 → 4.- List a. Its front node is compared with the front of b at each step.
- List b. The smaller front node (1 from a, then 2 from b, then 3 from a, then 4 from b) is attached to the result, and that list moves forward.
- The result starts at the dummy node, which is thrown away at the end (
dummy.nextis returned). When b runs out, the rest of a (just 5) is attached in one step.
Your turn: two practice problems
Try each on paper or in an editor first, with a timer set to 15 minutes. The solutions are hidden; each has tests in test_patterns.py that pass.
Return whether a linked list contains a cycle (a node whose arrow leads back to an earlier node), using O(1) extra memory.
Signal to look for: "Cycle" plus "O(1) space": fast and slow pointers.
Show a solution, with its tests
Step-by-step: what has_cycle does, in plain English
- Start both pointers at the head.
- Move slow by one and fast by two each turn.
- If they ever point at the same node, fast has lapped slow inside a loop.
- If fast reaches the end (None), there is no cycle.
# ── practice: has_cycle ──
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast: # the fast runner lapped the slow one
return True
return False
Time O(n), space O(1). The alternative, a set of visited nodes, is O(n) space; mention it, then say you can do better.
Merge two sorted linked lists into one sorted list by reusing the nodes.
Signal to look for: A "dummy head" node saves you from special-casing the first node.
Show a solution, with its tests
Step-by-step: what merge_sorted does, in plain English
- Create a dummy node and a
tailpointer that starts on it. - While both lists have nodes, attach the smaller front node to the tail and advance that list.
- When one list runs out, attach the rest of the other in one step.
- Return
dummy.next, the real head.
# ── practice: merge_sorted ──
def merge_sorted(a, b):
dummy = tail = ListNode() # dummy head avoids special-casing the first node
while a and b:
if a.val <= b.val:
tail.next, a = a, a.next
else:
tail.next, b = b, b.next
tail = tail.next
tail.next = a or b # attach whichever list still has nodes
return dummy.next
Time O(n + m), space O(1). The dummy head is a technique to remember: it removes the "is this the first node?" branch.
Quick reference — Linked lists
- The signal
- "Linked list", "head", "
.next", "in place", "cycle", "middle". - The routine
- Save
nxt, rewire, step: withprev,cur,nxt. - Fast and slow
- Fast moves two steps; finds the middle, or a cycle if they meet.
- Dummy head
- A fake first node so the real head needs no special case.
- Edge cases
- Empty list, one node, two nodes. Test all three.
05 · Week 2 · Pattern 8Trees: Recursion Down, Queues Across
A tree is a node with up to two children, each of which is itself a tree. That self-similar shape is why recursion fits so well, and why a queue is the right tool when you want to visit level by level.
Thursday is trees, the pattern Priya fears most because it means recursion, and recursion is where she froze last month. She finds a way in: a recursive function on a tree is three lines. Say what to return for an empty tree, trust the function on each child, and combine their answers. Once the three lines are automatic, depth-first problems are routine. The level-by-level kind uses a queue instead.
Signals: the words in the problem that point here
Read the problem statement for these clues. Any two of them together is usually enough to name the pattern:
- "Binary tree", "root", "left/right child", "BST"
- "Depth", "height", "path", "sum along a path"
- "Level by level", "right side view", "zigzag"
- "Validate", "invert", "same tree", "lowest common ancestor"
- Two ways to visit: depth first (recursion) and breadth first (queue)
[3, 9, 20, None, None, 15, 7]; the colours are the levels.- At the start of level 2 the queue holds nodes 9 and 20 and nothing else. The queue is a waiting line: first in, first out.
size = len(queue)is frozen before the inner loop. The number 2 says "this level has 2 nodes"; without it we could not tell where level 2 ends and level 3 begins.- While popping level 2, the children of 20 (15 and 7) join the back of the queue. They are next, and they form the third list:
[15, 7].
Fig. A3.18 shows the tree 3, 9, 20, 15, 7 with its levels coloured. The right half is the queue the level-order walk uses. When level 2 begins, the queue holds exactly 9 and 20 (marker 1). The number of waiting nodes, 2, is saved first (marker 2), so we know where the level ends.
Popping the level-2 nodes adds their children, 15 and 7, to the back (marker 3). Depth-first visiting (recursion) goes deep before wide; breadth-first (a queue) goes wide before deep. Choose by the question: "level by level" is breadth-first; "along a path" is depth-first.
The template: the shape to remember
Step-by-step: what the trees template does, in plain English
dfs_templatehandles the empty tree first: return a plain value (0 here).- For a real node, call itself on the left child and on the right child.
- You do not have to understand how the child calls work inside; trust them to return the right answer for their subtree.
- Combine the two results with this node (here: 1 + the larger).
- Every depth-first tree solution is this skeleton with a different base value and a different combine step.
# ── template: trees ──
def dfs_template(node):
if node is None: # base case first
return 0
left = dfs_template(node.left) # trust the recursion for each child
right = dfs_template(node.right)
return 1 + max(left, right) # combine the children's answers
The worked problem: Depth, Levels and Valid Search Trees
Problem. Given the root of a binary tree, (a) return its maximum depth, (b) return its values level by level, and (c) check whether it is a valid binary search tree (every left descendant smaller, every right descendant larger). Three short problems that between them cover both visiting styles.
Before the chunks, here is the depth recursion unrolled, because recursion is where Priya freezes. Fig. A3.19 writes the value each call returns next to its node. The same four lines run at every node (marker 1). Node 20 gets 1 from node 15 and 1 from node 7 and returns 1 + max(1, 1) = 2 (marker 2).
[3, 9, 20, None, None, 15, 7] with the value its max_depth call returns.- The same three-line routine runs at every node. You never trace the whole tree by hand; you trust that each child call returns the right answer for its subtree.
- Node 20 gets 1 from node 15 and 1 from node 7, so it returns 1 + max(1, 1) = 2. Missing children return 0, which is the base case that stops the recursion.
Build it in chunks
We build p08_trees.py in three chunks, one per problem.
-
Chunk 1 — the node, a builder from a list, and recursion for maximum depth
The three-line recursion in its simplest form, after the scaffolding that lets us write trees compactly in tests.
Step-by-step: what chunk 1 does, in plain English
TreeNodeholds a value and left/right children.buildcreates a tree from a level-order list whereNonemeans no child, using a queue.max_depth: an empty tree has depth 0 (the base case).- Otherwise the depth is 1 for this node plus the deeper of the two children.
- The main block builds the example tree and prints its depth.
p08_trees.py — chunk 1runs offlinefrom collections import deque # ── chunk 1: the node, a builder, and recursion for max depth ── class TreeNode: def __init__(self, val=0, left=None, right=None): self.val, self.left, self.right = val, left, right def build(values): """Build from a level-order list; None marks a missing child.""" if not values or values[0] is None: return None root = TreeNode(values[0]) queue = deque([root]) i = 1 while queue and i < len(values): node = queue.popleft() if i < len(values) and values[i] is not None: node.left = TreeNode(values[i]) queue.append(node.left) i += 1 if i < len(values) and values[i] is not None: node.right = TreeNode(values[i]) queue.append(node.right) i += 1 return root def max_depth(node): if node is None: # base case: an empty tree has depth 0 return 0 return 1 + max(max_depth(node.left), max_depth(node.right)) if __name__ == "__main__": t = build([3, 9, 20, None, None, 15, 7]) print(max_depth(t))Recursion: a function that calls itself on smaller pieces, with a base case to stop.
Run
python3 p08_trees.py. It prints 3.terminalactual output (this chunk adds)3 -
Chunk 2 — breadth first: visit the tree one level at a time
Some questions are about levels. A queue holds the nodes of the level being processed, and the trick is to freeze how many there are.
Step-by-step: what chunk 2 does, in plain English
- An empty tree has no levels.
queuestarts with the root.size = len(queue)fixes how many nodes belong to the current level.- Pop exactly that many, record their values, and add their children to the back.
- Each finished level goes into the answer.
p08_trees.py — chunk 2runs offline# ── chunk 2: BFS - visit the tree one level at a time ── def level_order(root): if root is None: return [] levels = [] queue = deque([root]) while queue: size = len(queue) # freeze how many nodes are on THIS level level = [] for _ in range(size): node = queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) levels.append(level) return levels if __name__ == "__main__": print(level_order(t))collections.dequeas a queue:popleft()is O(1).Run
python3 p08_trees.pywith chunks 1 to 2 in the file. It prints[[3], [9, 20], [15, 7]].terminalactual output (this chunk adds)[[3], [9, 20], [15, 7]] -
Chunk 3 — depth first with information passed down: is it a valid search tree?
The common mistake is to only compare a node with its direct children. A node must be inside the bounds set by all its ancestors, so we pass the bounds down.
Step-by-step: what chunk 3 does, in plain English
lowandhighstart unbounded (±infinity).- An empty subtree is valid.
- A node whose value is not strictly between
lowandhighbreaks the rule. - Going left, the node's own value becomes the new upper bound; going right, the new lower bound.
- Both subtrees must be valid.
- The main block tests one valid and one invalid tree.
p08_trees.py — chunk 3runs offline# ── chunk 3: DFS with information passed down - is this a valid search tree? ── def is_valid_bst(node, low=float("-inf"), high=float("inf")): if node is None: return True if not (low < node.val < high): # every node must sit inside the bounds its ancestors set return False return (is_valid_bst(node.left, low, node.val) and is_valid_bst(node.right, node.val, high)) if __name__ == "__main__": print(is_valid_bst(build([2, 1, 3])), is_valid_bst(build([5, 1, 4, None, None, 3, 6])))Default parameters used to pass information down the recursion.
Run
python3 p08_trees.pywith chunks 1 to 3 in the file. It printsTrue False: [2, 1, 3] is valid, and [5, 1, 4, None, None, 3, 6] is not (3 sits under 5's right child but is smaller than 5).terminalactual output (this chunk adds)True False
The whole program
Lines 5–41 are chunk 1, 42–65 are chunk 2, 66–77 are chunk 3. Every chunk starts with a # ── chunk n ── comment. This file lives at code/a3-dsa-reset/p08_trees.py, with its tests in test_patterns.py.
# Pattern 8 - trees: DFS (recursion) and BFS (a queue). Python 3.12.
from collections import deque
# ── chunk 1: the node, a builder, and recursion for max depth ──
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
def build(values):
"""Build from a level-order list; None marks a missing child."""
if not values or values[0] is None:
return None
root = TreeNode(values[0])
queue = deque([root])
i = 1
while queue and i < len(values):
node = queue.popleft()
if i < len(values) and values[i] is not None:
node.left = TreeNode(values[i])
queue.append(node.left)
i += 1
if i < len(values) and values[i] is not None:
node.right = TreeNode(values[i])
queue.append(node.right)
i += 1
return root
def max_depth(node):
if node is None: # base case: an empty tree has depth 0
return 0
return 1 + max(max_depth(node.left), max_depth(node.right))
if __name__ == "__main__":
t = build([3, 9, 20, None, None, 15, 7])
print(max_depth(t))
# ── chunk 2: BFS - visit the tree one level at a time ──
def level_order(root):
if root is None:
return []
levels = []
queue = deque([root])
while queue:
size = len(queue) # freeze how many nodes are on THIS level
level = []
for _ in range(size):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
levels.append(level)
return levels
if __name__ == "__main__":
print(level_order(t))
# ── chunk 3: DFS with information passed down - is this a valid search tree? ──
def is_valid_bst(node, low=float("-inf"), high=float("inf")):
if node is None:
return True
if not (low < node.val < high): # every node must sit inside the bounds its ancestors set
return False
return (is_valid_bst(node.left, low, node.val)
and is_valid_bst(node.right, node.val, high))
if __name__ == "__main__":
print(is_valid_bst(build([2, 1, 3])), is_valid_bst(build([5, 1, 4, None, None, 3, 6])))
3
[[3], [9, 20], [15, 7]]
True False
Read the output. The invalid tree has 4 as the right child of 5, and 3 as a child of 4. Comparing each node only with its parent looks fine (3 < 4), but 3 is in 5's right subtree, so it must be greater than 5. The bounds passed down catch it.
Complexity, said out loud
Time: each node is visited once in every one of the three: O(n). Space: depth-first uses O(h) stack space where h is the height: O(log n) for a balanced tree and O(n) for a tree that is a straight line. Breadth-first uses O(w) where w is the widest level.
Python's recursion limit (1,000) matters for a tree that is a straight line of 5,000 nodes. If the interviewer says "the tree can be very deep", switch to an explicit stack or queue and say why.
Your turn: two practice problems
Try each on paper or in an editor first, with a timer set to 15 minutes. The solutions are hidden; each has tests in test_patterns.py that pass.
Return whether some path from the root down to a leaf (a node with no children) has values that add up to a target. In the tree [5, 4, 8, 11, None, 13, 4, 7, 2] a path adds up to 22.
Signal to look for: "Along a path from the root": depth first, carrying the remaining target down.
Show a solution, with its tests
Step-by-step: what has_path_sum does, in plain English
- An empty tree has no path.
- At a leaf, the path works if the remaining target equals the leaf value.
- Otherwise subtract this node from the target and ask both children.
- Either child finding a path is enough: use
or.
# ── practice: has_path_sum ──
def has_path_sum(node, target):
if node is None:
return False
if node.left is None and node.right is None: # a leaf: the path ends here
return node.val == target
rest = target - node.val
return has_path_sum(node.left, rest) or has_path_sum(node.right, rest)
Time O(n), space O(h). Mind the word "leaf": a node with one child is not a leaf, so the path must go on.
Swap the left and right children of every node, so the tree becomes its own mirror image.
Signal to look for: "Every node" plus "same operation at each": a recursive skeleton.
Show a solution, with its tests
Step-by-step: what invert_tree does, in plain English
- An empty tree stays empty.
- Invert the right subtree and the left subtree recursively.
- Assign them swapped: the inverted right becomes the left child and vice versa.
- Return the node.
# ── practice: invert_tree ──
def invert_tree(node):
if node is None:
return None
node.left, node.right = invert_tree(node.right), invert_tree(node.left)
return node
Time O(n), space O(h). It is short on purpose: it tests whether you trust the recursion for the children.
Quick reference — Trees
- The signal
- "Binary tree", "depth", "path", "level by level", "BST".
- Depth first
- Base case for None; recurse left and right; combine.
- Breadth first
- A deque;
size = len(queue)before the inner loop. - Validate a BST
- Pass the (low, high) bounds down; do not just compare with the parent.
- Cost
- Time O(n); space O(height) for DFS, O(widest level) for BFS.
06 · Week 3 · Pattern 9Graphs: Breadth First, Depth First, and Ordering Tasks
A graph is things plus the links between them. Three questions cover most interview problems: what is the fewest steps (BFS), what is connected (DFS), and in what order must things happen (topological sort).
Week three, Monday: graphs, the pattern Priya has the least vocabulary for. A maze is not obviously a graph, and neither are course prerequisites. The cure is one habit: whenever a problem says "steps", "connected" or "must come before", ask "who are my neighbours?". If she can answer that, she can run one of three routines she already knows: a queue, a recursion, or a count of waiting prerequisites.
Signals: the words in the problem that point here
Read the problem statement for these clues. Any two of them together is usually enough to name the pattern:
- "Shortest path", "fewest moves/steps/hops" with equal-cost steps: BFS
- "Connected", "islands", "regions", "can I reach": DFS or BFS
- "Prerequisites", "dependencies", "order of tasks", "build order": topological sort
- "Grid", "maze", "board", "word ladder" (hidden graphs)
- "Cycle", "circular dependency"
shortest_path(maze) returns 4.- The start has distance 0. BFS spreads out in rings: every cell one step away is labelled 1 before any cell two steps away is touched.
- Cell (1,1) is 2 steps away: it can only be reached through (0,1), since (1,0) and (0,2) are walls. Walls simply are never added to the queue.
- The goal at the bottom-right has distance 4. Because BFS processes cells in order of distance, the first time it reaches the goal is guaranteed to be by the shortest route. DFS makes no such promise.
Fig. A3.20 labels each open cell of a 3 × 3 maze with its BFS distance from the top-left corner. The start is 0 (marker 1). Cell (1, 1) is 2 away because the only way in is through (0, 1) (marker 2). The goal is 4 steps away (marker 3).
BFS works in rings, like a ripple in water, because a queue serves cells in the order they were added. All distance-1 cells are processed before any distance-2 cell, so the first time the goal is taken from the queue is a shortest path. If you ever need a path rather than a count, store each cell's parent and walk back.
The template: the shape to remember
Step-by-step: what the graphs template does, in plain English
bfs_distancestakes a graph as a dict from each node to its list of neighbours, and a start node.distrecords the distance of every node reached so far; the start has 0. It doubles as the "visited" set.- Take a node from the front of the queue.
- For each neighbour not yet in
dist, set its distance to one more and add it to the back of the queue. - Marking when adding means each node enters the queue once.
# ── template: graphs ──
def bfs_distances(graph, start):
dist = {start: 0}
queue = deque([start])
while queue:
node = queue.popleft()
for nxt in graph[node]:
if nxt not in dist: # mark when enqueued, so each node enters once
dist[nxt] = dist[node] + 1
queue.append(nxt)
return dist
The worked problem: Shortest Path in a Maze, and a Task Order
Problem. Given a grid with 0 for open and 1 for wall, return the fewest steps from the top-left to the bottom-right (moving up, down, left or right), or −1 if it is impossible. Then: given n tasks and pairs saying which must come first, return a valid order, or nothing if impossible.
Build it in chunks
We build p09_graphs.py in three chunks.
-
Chunk 1 — a grid is a graph: list the neighbours of a cell
Every graph problem starts with "who are my neighbours?". Writing that as a function lets the rest of the code ignore the grid.
Step-by-step: what chunk 1 does, in plain English
- Try the four moves: down, up, right, left.
- Compute the new row and column.
- Keep the move only if it stays on the grid and the cell is open (0).
yieldhands back each neighbour one at a time instead of building a list.- The main block lists the neighbours of the top-left cell of a small maze.
p09_graphs.py — chunk 1runs offlinefrom collections import deque # ── chunk 1: a grid is a graph - list the neighbours of a cell ── def neighbours(grid, r, c): for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] == 0: yield nr, nc # only open cells (0); walls are 1 if __name__ == "__main__": maze = [[0, 0, 1], [1, 0, 0], [0, 0, 0]] print(list(neighbours(maze, 0, 0)))yield— a function that produces values lazily (a generator).Run
python3 p09_graphs.py. It prints[(0, 1)]: the cell below is a wall, so only the right neighbour is open.terminalactual output (this chunk adds)[(0, 1)] -
Chunk 2 — BFS gives the shortest path in steps
The neighbour function is the only place that knows about grids. The BFS loop works for any graph.
Step-by-step: what chunk 2 does, in plain English
- If the start is a wall, there is no path.
- The goal is the bottom-right cell.
- The queue holds pairs: a cell and the steps taken to reach it.
visitedholds cells already added; a cell is marked when it is added, so it is added once.- Take cells from the front; when one is the goal, return its steps.
- Otherwise add each unvisited neighbour with steps + 1.
- If the queue empties without reaching the goal, return −1.
p09_graphs.py — chunk 2runs offline# ── chunk 2: BFS gives the shortest path in steps ── def shortest_path(grid): if grid[0][0] == 1: return -1 goal = (len(grid) - 1, len(grid[0]) - 1) queue = deque([((0, 0), 0)]) # (cell, steps taken so far) visited = {(0, 0)} # mark when we ENQUEUE, so a cell enters at most once while queue: (r, c), steps = queue.popleft() if (r, c) == goal: return steps for nxt in neighbours(grid, r, c): if nxt not in visited: visited.add(nxt) queue.append((nxt, steps + 1)) return -1 if __name__ == "__main__": print(shortest_path(maze), shortest_path([[0, 1], [1, 0]]))dequeas a queue (popleft); asetas the visited marks.Run
python3 p09_graphs.pywith chunks 1 to 2 in the file. It prints4 -1: 4 steps for the maze, and −1 for a maze with the exits blocked.terminalactual output (this chunk adds)4 -1 -
Chunk 3 — topological sort: order tasks so every prerequisite comes first
A different question on a different kind of graph: not distance, but order. The routine is a count of how many prerequisites each task is still waiting for.
Step-by-step: what chunk 3 does, in plain English
after[b]lists the tasks that come after task b;waiting_on[a]counts the prerequisites a still needs.- Fill both from the pairs
(a, b)meaning "b before a". - Tasks with nothing to wait for go into the ready queue.
- Take a ready task, add it to the order, and reduce the count of every task that was waiting on it.
- A task whose count reaches 0 becomes ready.
- If every task was placed, return the order; otherwise there is a cycle, so return an empty list.
p09_graphs.py — chunk 3runs offline# ── chunk 3: topological sort - order tasks so every prerequisite comes first ── def topo_order(n, prereqs): """prereqs is a list of (a, b) meaning 'b must come before a'. Returns [] on a cycle.""" after = [[] for _ in range(n)] waiting_on = [0] * n # how many prerequisites each task still has for a, b in prereqs: after[b].append(a) waiting_on[a] += 1 ready = deque(i for i in range(n) if waiting_on[i] == 0) order = [] while ready: t = ready.popleft() order.append(t) for nxt in after[t]: waiting_on[nxt] -= 1 if waiting_on[nxt] == 0: ready.append(nxt) return order if len(order) == n else [] if __name__ == "__main__": print(topo_order(4, [(1, 0), (2, 0), (3, 1), (3, 2)]), topo_order(2, [(0, 1), (1, 0)]))Counting incoming edges (the "in-degree") instead of searching.
Run
python3 p09_graphs.pywith chunks 1 to 3 in the file. It prints[0, 1, 2, 3] []: an order for four tasks, and an empty list for two tasks that need each other.terminalactual output (this chunk adds)[0, 1, 2, 3] []
The whole program
Lines 5–19 are chunk 1, 20–41 are chunk 2, 42–63 are chunk 3. Every chunk starts with a # ── chunk n ── comment. This file lives at code/a3-dsa-reset/p09_graphs.py, with its tests in test_patterns.py.
# Pattern 9 - graphs: BFS shortest path, DFS flood fill, topological sort. Python 3.12.
from collections import deque
# ── chunk 1: a grid is a graph - list the neighbours of a cell ──
def neighbours(grid, r, c):
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] == 0:
yield nr, nc # only open cells (0); walls are 1
if __name__ == "__main__":
maze = [[0, 0, 1],
[1, 0, 0],
[0, 0, 0]]
print(list(neighbours(maze, 0, 0)))
# ── chunk 2: BFS gives the shortest path in steps ──
def shortest_path(grid):
if grid[0][0] == 1:
return -1
goal = (len(grid) - 1, len(grid[0]) - 1)
queue = deque([((0, 0), 0)]) # (cell, steps taken so far)
visited = {(0, 0)} # mark when we ENQUEUE, so a cell enters at most once
while queue:
(r, c), steps = queue.popleft()
if (r, c) == goal:
return steps
for nxt in neighbours(grid, r, c):
if nxt not in visited:
visited.add(nxt)
queue.append((nxt, steps + 1))
return -1
if __name__ == "__main__":
print(shortest_path(maze), shortest_path([[0, 1], [1, 0]]))
# ── chunk 3: topological sort - order tasks so every prerequisite comes first ──
def topo_order(n, prereqs):
"""prereqs is a list of (a, b) meaning 'b must come before a'. Returns [] on a cycle."""
after = [[] for _ in range(n)]
waiting_on = [0] * n # how many prerequisites each task still has
for a, b in prereqs:
after[b].append(a)
waiting_on[a] += 1
ready = deque(i for i in range(n) if waiting_on[i] == 0)
order = []
while ready:
t = ready.popleft()
order.append(t)
for nxt in after[t]:
waiting_on[nxt] -= 1
if waiting_on[nxt] == 0:
ready.append(nxt)
return order if len(order) == n else []
if __name__ == "__main__":
print(topo_order(4, [(1, 0), (2, 0), (3, 1), (3, 2)]), topo_order(2, [(0, 1), (1, 0)]))
[(0, 1)]
4 -1
[0, 1, 2, 3] []
Read the output. The maze answer, 4, is the number from the figure. For the topological sort, any order that puts 0 first and 3 last is correct; the program returns one of them. An interviewer may ask "is the answer unique?" and the answer is no: tasks 1 and 2 could swap.
Complexity, said out loud
Time: BFS touches each cell once and looks at 4 neighbours: O(rows × cols). Topological sort touches each task and each prerequisite once: O(V + E), where V is the number of nodes and E the number of links. Space: O(V) for the queue and visited marks.
Choose the tool by the question. "Fewest steps": BFS. "Is X reachable, how many groups": DFS or BFS, either. "Order with dependencies": topological sort. If steps have different costs, say "that needs Dijkstra's algorithm, which is BFS with a heap", and you will have shown you know the boundary.
Counting groups is the other graph routine, and the picture is simple. Fig. A3.21 scans a grid of land and water. The outer loops find an unseen land cell (marker 1), a flood fill marks its whole island (marker 2), and the count of fills is the answer (marker 3).
count_islands on four rows of land and water; each land cell shows its island number.- The outer loops visit every cell once. The first land cell found (top-left) starts island 1.
- The flood fill (a DFS) spreads from that cell to every connected land cell up, down, left and right, marking them all, so the outer loop will not count them again.
- Each unmarked land cell the loops meet afterwards is a brand new island. Here that gives islands 2 and 3, so the answer is 3.
Questions you might be asking now
Graphs raise four questions that most explanations skip. Each answer uses the same 4 × 4 grid, shown once here, and the numbers come from followup_numbers.py.
| col 0 | col 1 | col 2 | col 3 | |
|---|---|---|---|---|
| row 0 | 0 (start) | 0 | 0 | 0 |
| row 1 | 0 | 0 | 0 | 0 |
| row 2 | 0 | 0 | 1 | 1 |
| row 3 | 0 | 0 | 0 | 0 (goal) |
Is a grid really a "graph"? I do not see any nodes or edges.
Yes. Every cell is a node, and every pair of neighbouring open cells is an edge. Nothing needs to be stored: the neighbours function lists the edges of a cell when asked.
A graph is only "things" and "which things connect to which". Using the grid above:
- Nodes. The 16 cells, named by (row, column). Walls are cells we refuse to enter, so effectively 14 nodes.
- Edges. Cell (0, 0) connects to (0, 1) and (1, 0): two neighbours. Up and left fall off the grid.
- Cell (2, 1). Neighbours: (3, 1) below, (1, 1) above, (2, 0) left. Right is (2, 2), a wall, so it is not an edge.
- The same thing as a dict. The grid is equivalent to
{(0,0): [(0,1), (1,0)], ...}. Building that dict is optional; the function computes it on demand.
The same trick works for words (one-letter changes), cities (roads), or tasks (prerequisites).
If you can answer "who are my neighbours?", you have a graph; you do not need to build one.
Why does BFS give the shortest path but DFS may not?
BFS visits cells in rings: everything one step away, then everything two steps away. The first time it reaches the goal, it did so through the fewest steps. DFS dives along one route and stops at the first success, which may be a long way round.
Run both on the 4 × 4 grid. DFS tries right, down, left, up in that order:
- DFS, going right first. It follows (0,0) → (0,1) → (0,2) → (0,3), then has to go down to (1,3), left to (1,2) and (1,1), down to (2,1) and (3,1), and right to (3,2) and (3,3). That is 10 steps.
- BFS. It labels all cells by distance. The goal is reached by going down the left side or through the middle: 6 steps.
- Compare. 10 steps against 6. Both found a valid path; only BFS promises the shortest.
- BFS spreads outwards in rings, so the goal is reached by a route with the fewest steps: along the top, down the middle column, then along the bottom, 6 steps.
- DFS tries right first, so it runs along the whole top row, steps down at the right edge, doubles back along row 1, then goes down column 1 and along the bottom: 10 steps. It is a valid path, just not a short one.
The honest limit: this holds for graphs where every step costs the same. If steps have different costs (road distances), BFS is not enough and you need Dijkstra's algorithm, which is BFS with a heap in place of the queue. DFS is not wrong, it just answers a different question: "is there a path?" and "visit everything".
BFS for fewest steps, DFS for "is it reachable" and "explore everything".
Why do we mark a cell as visited when we add it to the queue, not when we take it out?
Because otherwise the same cell can be added several times before it is taken out. Marking at the moment of adding guarantees each cell enters the queue at most once.
Use a small diamond graph: a connects to b and c, and both b and c connect to d. We count queue entries:
- Mark when popped. Start [a]. Pop a, add b and c. Pop b, d is not marked yet, add d. Pop c, d is still not marked (it is waiting in the queue), add d again. The queue held d twice: 5 pushes in all, 5 nodes processed.
- Mark when added. Pop a, add b and c (both marked now). Pop b, add d and mark it. Pop c, d is already marked, skip. 4 pushes in all, 4 nodes processed.
- At scale. On a grid where a cell has 4 neighbours, a cell could be added up to 4 times, and the duplicates multiply as levels grow.
- When d is only marked on being popped, b and c both see d as "not visited" while the first d still waits in the queue, so d goes in twice (red).
- When d is marked the moment it is added, c finds it already marked and skips it. Each node enters once. On a big grid this is the difference between 16 million and 4 times 16 million queue entries in the worst case.
The result of the program is still right either way; only the work is wasted, and in a large grid enough to cause a time-out.
Mark on enqueue: a node enters the queue once.
How does topological sort know there is a cycle?
It counts. A task can only be placed in the order once all its prerequisites are placed. In a cycle, each task waits for another in the loop, so none ever becomes ready, and the output ends up shorter than the number of tasks.
Take two tasks that each need the other: topo_order(2, [(0, 1), (1, 0)]).
- Count prerequisites. Task 0 needs task 1 (waiting on 1). Task 1 needs task 0 (waiting on 1).
- Find tasks that are ready. A task is ready when it waits on 0. Neither is: the ready queue starts empty.
- Result. No task is ever placed, so the order has 0 tasks while we expected 2. 0 < 2 means a cycle, and the function returns the empty list.
- A normal case. For four tasks
(1,0), (2,0), (3,1), (3,2)the order is[0, 1, 2, 3]: task 0 first (it has no prerequisites), then 1 and 2, and 3 last.
topo_order: a normal case (left) and a cycle (right).- Each task carries a count of unmet prerequisites. Task 0 waits on nothing, so it is the only one ready at the start; task 3 waits on both 1 and 2.
- Placing a task reduces the count of everything waiting on it. 3 only becomes ready after both 1 and 2 are placed, which is why it always comes last.
- In a cycle every task waits on another, so none ever has a count of 0. The order stays shorter than the number of tasks, and that gap is the cycle detector.
This is the same cycle check that build tools and package managers perform to report "circular dependency".
If the order is shorter than the number of tasks, some tasks are stuck in a cycle.
Your turn: two practice problems
Try each on paper or in an editor first, with a timer set to 15 minutes. The solutions are hidden; each has tests in test_patterns.py that pass.
A grid holds "1" for land and "0" for water. Count the islands: groups of land cells connected up, down, left or right.
Signal to look for: "Connected groups": flood-fill each unseen piece of land and count the fills.
Show a solution, with its tests
Step-by-step: what count_islands does, in plain English
seenremembers land cells already assigned to an island.dfs(r, c)returns at once if off the grid, on water, or already seen.- Otherwise it marks the cell and recurses to the four neighbours: the whole island gets marked.
- The outer loops scan every cell; each unseen land cell starts a new island, so add 1 and flood.
# ── practice: count_islands ──
def count_islands(grid):
seen = set()
def dfs(r, c):
if not (0 <= r < len(grid) and 0 <= c < len(grid[0])):
return
if grid[r][c] != "1" or (r, c) in seen:
return
seen.add((r, c))
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
dfs(r + dr, c + dc)
islands = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == "1" and (r, c) not in seen:
islands += 1
dfs(r, c)
return islands
Time O(rows × cols), since every cell is seen once. Space O(rows × cols) in the worst case for the recursion; a huge all-land grid could hit Python's recursion limit, so for big inputs use an explicit stack or BFS instead.
There are n courses and a list of pairs (a, b) meaning you must take b before a. Return whether every course can be completed.
Signal to look for: "Prerequisites" and "possible?": topological sort, and a cycle means impossible.
Show a solution, with its tests
Step-by-step: what can_finish does, in plain English
- Run the topological sort from the worked problem.
- If it placed all n courses, the answer is yes.
- If it placed fewer, some courses wait on each other in a cycle: no.
# ── practice: can_finish ──
def can_finish(n, prereqs):
return len(topo_order(n, prereqs)) == n
Time O(V + E). This is a one-line reuse of the worked problem, which is the point: recognise the pattern and reuse the routine.
Quick reference — Graphs
- The signal
- "Fewest steps", "connected", "islands", "prerequisites", "order".
- Make the graph
- Write
neighbours(node); a grid, a word list and a dict are all graphs. - BFS
- Queue plus visited; mark on enqueue; first arrival at the goal is shortest (equal-cost steps).
- DFS
- Recursion or a stack plus visited; for reachability and counting groups.
- Topological sort
- Count each task's unmet prerequisites; place ready ones; shorter output than n means a cycle.
- Cost
- Time O(V + E), space O(V).
06 · Week 3 · Pattern 10Heaps: Always Know the Smallest, Keep Only the Best k
A heap is a container that always hands you its smallest item first, and can add or remove one in O(log n). It is the tool for "top k", "k-th largest" and "merge sorted streams".
Tuesday is heaps. Priya has used priority queues indirectly (job schedulers) but never by name. Her habit is to sort everything and take the top few, which works and costs O(n log n). The interviewer will ask "can you do better when k is small?" The answer is a heap of size k: it never holds more than k items, so each step costs log k instead of log n.
Signals: the words in the problem that point here
Read the problem statement for these clues. Any two of them together is usually enough to name the pattern:
- "Top k", "k most frequent", "k largest/smallest"
- "K-th largest element"
- "Merge k sorted lists/streams"
- "Running median", "always the smallest/largest so far"
- "Schedule", "next event", "priority"
[1,1,1,2,2,3]; counts are 1 → 3, 2 → 2, 3 → 1.- After the first value the heap has one pair. A heap of (count, value) pairs keeps the smallest count on top, ready to be removed.
- After the second push the top is (2, 2), the weaker of the two. Nothing is evicted yet because the size is 2, not more than k.
- Pushing (1, 3) makes size 3, one too many. The pop removes the smallest count, which is the new pair itself. The heap never holds more than k = 2 items, so each push or pop costs log 2, not log n.
Fig. A3.25 traces "top 2 most frequent" in [1, 1, 1, 2, 2, 3]. Counts are 1 → 3, 2 → 2 and 3 → 1. Each pair (count, value) is pushed. After the first two pushes the heap holds two pairs (marker 2). Pushing the third makes three, one too many (marker 3).
The trick is which item you evict: the weakest. A min-heap keeps its smallest item on top, so popping it removes the weakest of the current candidates. That sounds backwards ("a min-heap for the biggest k?") and is the most common point of confusion. To keep the k largest, evict the smallest.
The template: the shape to remember
Step-by-step: what the heaps template does, in plain English
k_largestkeeps a list calledheap, used throughheapqfunctions.heappushadds an item; the smallest is always atheap[0].- Whenever the heap has more than k items,
heappopremoves the smallest. - After all items, the heap holds exactly the k largest; sort them for display.
- Python has only a min-heap. For a max-heap, push negated numbers.
# ── template: heaps ──
def k_largest(nums, k):
heap = [] # min-heap holding the k largest seen so far
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap) # drop the smallest of k+1
return sorted(heap, reverse=True)
The worked problem: Top K Frequent Elements
Problem. Given a list of numbers and k, return the k most frequent values. [1, 1, 1, 2, 2, 3] with k = 2 gives [1, 2].
We start by watching the heap on its own, then solve the problem by sorting (simple and correct), then replace the sort with a heap of size k.
A heap looks magical until you see where it keeps its items: in an ordinary list, read as a tree. Fig. A3.26 pushes 2 onto [1, 3, 5, 8, 9]. The value lands at the end (marker 1) and swaps once with a bigger parent (marker 2). That is all heappush does.
- The new value goes at the end of the list, which is the next free spot in the bottom row of the tree.
- Then it swaps with its parent while the parent is bigger. One swap was enough here, so the cost is the height of the tree, about log₂ n. The tree is never stored as nodes; the list positions are the tree.
The first chunk below uses heapq, which you have not met. You are not expected to know it yet: chunk 1 shows it alone, and the step-by-step list explains each call.
Build it in chunks
We build p10_heaps.py in three chunks.
-
Chunk 1 — the heap in four lines
Before using a heap for anything, see what one does: push in any order, take out smallest first.
Step-by-step: what chunk 1 does, in plain English
heappushadds each of four numbers to the listh.- After the pushes,
h[0]is the smallest, 1. heappopremoves and returns the smallest, twice (1, then 3).h[0]now shows the next smallest, 5.
p10_heaps.py — chunk 1runs offlineimport heapq from collections import Counter # ── chunk 1: the heap in four lines ── if __name__ == "__main__": h = [] for x in [5, 1, 8, 3]: heapq.heappush(h, x) # a min-heap: the smallest value is always h[0] print(h[0], heapq.heappop(h), heapq.heappop(h), h[0])heapq.heappush,heapq.heappopand peeking ath[0].Run
python3 p10_heaps.py. It prints1 1 3 5: the smallest, then the two pops, then the new smallest.terminalactual output (this chunk adds)1 1 3 5 -
Chunk 2 — top k frequent by sorting everything (simple, O(n log n))
A correct version first, and it is also a good first thing to say to the interviewer.
Step-by-step: what chunk 2 does, in plain English
Countercounts how many times each number appears.- Sort the distinct numbers by count, biggest first (the minus sign reverses the order).
- Take the first k.
p10_heaps.py — chunk 2runs offline# ── chunk 2: top k frequent by sorting everything (simple, O(n log n)) ── def top_k_sorting(nums, k): counts = Counter(nums) ranked = sorted(counts, key=lambda v: -counts[v]) return ranked[:k] if __name__ == "__main__": print(top_k_sorting([1, 1, 1, 2, 2, 3], 2))Counterandsorted(..., key=...).Run
python3 p10_heaps.pywith chunks 1 to 2 in the file. It prints[1, 2].terminalactual output (this chunk adds)[1, 2] -
Chunk 3 — keep only a heap of size k (O(n log k))
Sorting orders every distinct value although we only want k of them. A heap of size k does less work when k is small.
Step-by-step: what chunk 3 does, in plain English
- Count the values.
- For each value, push the pair
(count, value)onto the heap. - If the heap has more than k pairs, pop the one with the smallest count.
- The pairs left are the k most frequent; sort them biggest first and return only the values.
- The main block also tries a single-value list.
p10_heaps.py — chunk 3runs offline# ── chunk 3: keep only a heap of size k (O(n log k)) ── def top_k_frequent(nums, k): counts = Counter(nums) heap = [] # holds (count, value); the smallest count sits on top for value, count in counts.items(): heapq.heappush(heap, (count, value)) if len(heap) > k: heapq.heappop(heap) # evict the weakest of the k+1 return [v for _, v in sorted(heap, reverse=True)] if __name__ == "__main__": print(top_k_frequent([1, 1, 1, 2, 2, 3], 2), top_k_frequent([7], 1))Pushing tuples: Python compares the first element (the count) first.
Run
python3 p10_heaps.pywith chunks 1 to 3 in the file. It prints[1, 2] [7].terminalactual output (this chunk adds)[1, 2] [7]
The whole program
Lines 6–13 are chunk 1, 14–24 are chunk 2, 25–37 are chunk 3. Every chunk starts with a # ── chunk n ── comment. This file lives at code/a3-dsa-reset/p10_heaps.py, with its tests in test_patterns.py.
# Pattern 10 - heaps and top-k. Python 3.12, standard library only.
import heapq
from collections import Counter
# ── chunk 1: the heap in four lines ──
if __name__ == "__main__":
h = []
for x in [5, 1, 8, 3]:
heapq.heappush(h, x) # a min-heap: the smallest value is always h[0]
print(h[0], heapq.heappop(h), heapq.heappop(h), h[0])
# ── chunk 2: top k frequent by sorting everything (simple, O(n log n)) ──
def top_k_sorting(nums, k):
counts = Counter(nums)
ranked = sorted(counts, key=lambda v: -counts[v])
return ranked[:k]
if __name__ == "__main__":
print(top_k_sorting([1, 1, 1, 2, 2, 3], 2))
# ── chunk 3: keep only a heap of size k (O(n log k)) ──
def top_k_frequent(nums, k):
counts = Counter(nums)
heap = [] # holds (count, value); the smallest count sits on top
for value, count in counts.items():
heapq.heappush(heap, (count, value))
if len(heap) > k:
heapq.heappop(heap) # evict the weakest of the k+1
return [v for _, v in sorted(heap, reverse=True)]
if __name__ == "__main__":
print(top_k_frequent([1, 1, 1, 2, 2, 3], 2), top_k_frequent([7], 1))
1 1 3 5
[1, 2]
[1, 2] [7]
Read the output. Both solutions give [1, 2]. Their difference is not visible on six numbers, only on a million: with 1,000,000 distinct values and k = 10, the sort handles a million items and the heap never holds more than 10.
Complexity, said out loud
Time: counting is O(n). The heap version does up to n pushes and pops on a heap of size at most k: O(n log k). Sorting would be O(n log n). Space: O(n) for the counts, O(k) for the heap.
Say when each is right: "for small k I use a heap of size k; if k is close to n, sorting is simpler and as fast." Python also has heapq.nlargest(k, items), which does this for you: mention it, but show the loop so the interviewer sees you understand it.
Your turn: two practice problems
Try each on paper or in an editor first, with a timer set to 15 minutes. The solutions are hidden; each has tests in test_patterns.py that pass.
Return the k-th largest number in an unsorted list (the 2nd largest of [3, 2, 1, 5, 6, 4] is 5).
Signal to look for: "K-th largest" is the smallest of the top k: a min-heap of size k keeps exactly that on top.
Show a solution, with its tests
Step-by-step: what kth_largest does, in plain English
- Take the first k numbers as the starting heap and
heapifyit (O(k)). - For each remaining number, if it beats the smallest in the heap, replace that smallest with it.
- At the end the top of the heap is the k-th largest.
# ── practice: kth_largest ──
def kth_largest(nums, k):
heap = nums[:k]
heapq.heapify(heap) # smallest of the k biggest sits on top
for x in nums[k:]:
if x > heap[0]:
heapq.heapreplace(heap, x)
return heap[0]
Time O(n log k), space O(k). A different method, quickselect, averages O(n); the heap version is the one to write first because it is hard to get wrong.
Merge k sorted Python lists into one sorted list: [[1, 4, 5], [1, 3, 4], [2, 6]] becomes [1, 1, 2, 3, 4, 4, 5, 6].
Signal to look for: "Merge k sorted": the heap holds the front item of each list.
Show a solution, with its tests
Step-by-step: what merge_k_sorted does, in plain English
- Push the first item of each non-empty list as
(value, which list, position). - Pop the smallest, add it to the output.
- Push the next item from the same list, if any.
- Repeat until the heap is empty.
# ── practice: merge_k_sorted ──
def merge_k_sorted(lists):
heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
heapq.heapify(heap)
out = []
while heap:
value, i, j = heapq.heappop(heap)
out.append(value)
if j + 1 < len(lists[i]):
heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
return out
Time O(N log k) for N items in total; space O(k) for the heap. The extra tuple fields (which list, which position) are what let you refill from the right list.
Quick reference — Heaps
- The signal
- "Top k", "k-th largest", "merge k sorted", "always the smallest so far".
- The tool
heapq:heappush,heappop,heapify, peekh[0].- Top k largest
- Min-heap of size k; evict the smallest when size exceeds k.
- Max-heap
- Push negated numbers; negate again on the way out.
- Cost
- Push/pop O(log size); top-k in O(n log k); space O(k).
06 · Week 3 · Pattern 11Intervals: Sort by Start, Then Compare Neighbours
An interval is a stretch with a start and an end, like a meeting. Almost every interval problem becomes easy after you sort by start time, because overlapping stretches then sit next to each other.
Wednesday: intervals. Priya recognises this one from calendar and booking features she has built, and her instinct is to compare every meeting with every other, which is O(n²). The pattern replaces that with one sort and one pass. The question she must learn to ask is "what does sorting buy me?", and here it buys neighbours.
Signals: the words in the problem that point here
Read the problem statement for these clues. Any two of them together is usually enough to name the pattern:
- "Meetings", "bookings", "time ranges", "[start, end]" pairs
- "Merge overlapping", "insert interval"
- "Minimum number of rooms/platforms/CPUs"
- "Can a person attend all?", "any overlap?"
- "Remove the fewest to avoid overlap"
merge_intervals returns [[1, 6], [8, 10], [15, 18]].- The four intervals after sorting by start. Sorting is what lets us compare each interval with only the last merged one, never with all the others.
- The three merged intervals. [1,3] and [2,6] touch, so they became [1,6]; the others stood alone.
- The overlap test is one comparison: does this interval start at or before the end of the last merged one? If yes, stretch that end with
max: taking the maximum matters when one interval sits entirely inside another.
Fig. A3.27 shows four meetings sorted by start (marker 1) and the three that result after merging (marker 2). Only the first two touch. Because the list is sorted by start, a new interval can only overlap the last merged one, never an older one.
The overlap test is a single comparison (marker 3): does this interval start at or before the end of the last merged one? If so, stretch that end to the larger of the two ends. If not, start a new merged interval.
The template: the shape to remember
Step-by-step: what the intervals template does, in plain English
sweep_intervalssorts the intervals by start (Python sorts lists of pairs by the first element).- Walk through them with an output list.
- If the output is not empty and this interval starts at or before the last output interval's end, they overlap: set that end to the larger end.
- Otherwise append this interval as a new one.
# ── template: intervals ──
def sweep_intervals(intervals):
out = []
for start, end in sorted(intervals):
if out and start <= out[-1][1]:
out[-1][1] = max(out[-1][1], end)
else:
out.append([start, end])
return out
The worked problem: Merge Overlapping Meetings
Problem. Given a list of [start, end] meetings, merge all that overlap and return the result in order. [[8,10],[1,3],[2,6],[15,18]] gives [[1,6],[8,10],[15,18]]. Then: the fewest rooms needed so no two overlapping meetings share one.
The room-counting problem in chunk 3 is easiest to see as rooms on a timeline. Fig. A3.28 draws it. Room 1 is taken all day by the first meeting (marker 1), the second meeting needs room 2 (marker 2), and the third reuses room 2 once it is free (marker 3).
min_rooms([[0,30],[5,10],[15,20]]): two rooms are enough.- Meeting [0, 30] takes room 1 and holds it all day, so any meeting that starts before 30 needs another room.
- Meeting [5, 10] starts while room 1 is busy, so it opens room 2. At 10 that room is free again.
- Meeting [15, 20] finds the earliest-freeing room (room 2, free since 10) and reuses it. The heap of end times is [20, 30], size 2, which is the answer.
Build it in chunks
We build p11_intervals.py in three chunks.
-
Chunk 1 — sort by start, so overlaps become neighbours
The whole pattern depends on this one line. Look at what it does to a shuffled list.
Step-by-step: what chunk 1 does, in plain English
meetingsis a shuffled list of four meetings.sorted(meetings)orders pairs by start time (ties by end).- The main block prints the sorted list.
p11_intervals.py — chunk 1runs offlineimport heapq # ── chunk 1: sort by start time, so overlaps become neighbours ── if __name__ == "__main__": meetings = [[8, 10], [1, 3], [2, 6], [15, 18]] print(sorted(meetings))Sorting a list of pairs: Python compares the first elements, then the second.
Run
python3 p11_intervals.py. It prints the meetings sorted by start:[[1, 3], [2, 6], [8, 10], [15, 18]].terminalactual output (this chunk adds)[[1, 3], [2, 6], [8, 10], [15, 18]] -
Chunk 2 — merge overlapping intervals
With neighbours adjacent, one pass is enough: each interval either stretches the last result or starts a new one.
Step-by-step: what chunk 2 does, in plain English
mergedis the answer so far.- Loop over the intervals in start order.
- If this one starts at or before the end of the last merged interval, stretch that end with
max(it may even be entirely inside, in which case the end does not change). - Otherwise start a new merged interval.
- The main block merges the four meetings, touches-at-the-edge
[[1, 4], [4, 5]], and an empty list.
p11_intervals.py — chunk 2runs offline# ── chunk 2: merge overlapping intervals ── def merge_intervals(intervals): merged = [] for start, end in sorted(intervals): if merged and start <= merged[-1][1]: # overlaps the last merged one merged[-1][1] = max(merged[-1][1], end) # stretch it else: merged.append([start, end]) return merged if __name__ == "__main__": print(merge_intervals(meetings), merge_intervals([[1, 4], [4, 5]]), merge_intervals([]))maxto extend an end without shrinking it.Run
python3 p11_intervals.pywith chunks 1 to 2 in the file. It prints the merged intervals, then[[1, 5]](touching counts as overlapping here) and an empty list.terminalactual output (this chunk adds)[[1, 6], [8, 10], [15, 18]] [[1, 5]] [] -
Chunk 3 — how many rooms do the meetings need at the busiest moment?
A new question on the same sorted list. A min-heap of end times tells us which room frees up first.
Step-by-step: what chunk 3 does, in plain English
endsis a min-heap of the end times of rooms in use.- For each meeting in start order, look at the room that frees earliest,
ends[0]. - If it is free by now (
ends[0] <= start), reuse it: replace its end time with this meeting's end. - If nobody is free, open a new room by pushing the end time.
- The heap size at the end is the number of rooms.
p11_intervals.py — chunk 3runs offline# ── chunk 3: how many rooms do the meetings need at the busiest moment? ── def min_rooms(intervals): ends = [] # min-heap of end times of rooms in use for start, end in sorted(intervals): if ends and ends[0] <= start: heapq.heapreplace(ends, end) # the earliest-finishing room is free: reuse it else: heapq.heappush(ends, end) # nobody is free: open a new room return len(ends) if __name__ == "__main__": print(min_rooms([[0, 30], [5, 10], [15, 20]]), min_rooms([[7, 10], [2, 4]]))heapq.heapreplace— pop the smallest and push a new one in one step.Run
python3 p11_intervals.pywith chunks 1 to 3 in the file. It prints2 1: two rooms for[[0,30],[5,10],[15,20]]and one room for two non-overlapping meetings.terminalactual output (this chunk adds)2 1
The whole program
Lines 5–10 are chunk 1, 11–25 are chunk 2, 26–38 are chunk 3. Every chunk starts with a # ── chunk n ── comment. This file lives at code/a3-dsa-reset/p11_intervals.py, with its tests in test_patterns.py.
# Pattern 11 - intervals. Python 3.12, standard library only.
import heapq
# ── chunk 1: sort by start time, so overlaps become neighbours ──
if __name__ == "__main__":
meetings = [[8, 10], [1, 3], [2, 6], [15, 18]]
print(sorted(meetings))
# ── chunk 2: merge overlapping intervals ──
def merge_intervals(intervals):
merged = []
for start, end in sorted(intervals):
if merged and start <= merged[-1][1]: # overlaps the last merged one
merged[-1][1] = max(merged[-1][1], end) # stretch it
else:
merged.append([start, end])
return merged
if __name__ == "__main__":
print(merge_intervals(meetings), merge_intervals([[1, 4], [4, 5]]), merge_intervals([]))
# ── chunk 3: how many rooms do the meetings need at the busiest moment? ──
def min_rooms(intervals):
ends = [] # min-heap of end times of rooms in use
for start, end in sorted(intervals):
if ends and ends[0] <= start:
heapq.heapreplace(ends, end) # the earliest-finishing room is free: reuse it
else:
heapq.heappush(ends, end) # nobody is free: open a new room
return len(ends)
if __name__ == "__main__":
print(min_rooms([[0, 30], [5, 10], [15, 20]]), min_rooms([[7, 10], [2, 4]]))
[[1, 3], [2, 6], [8, 10], [15, 18]]
[[1, 6], [8, 10], [15, 18]] [[1, 5]] []
2 1
Read the output. For the room problem, the meeting 0–30 stays all day, so 5–10 needs a second room, and 15–20 reuses the second one after it frees at 10. Two rooms. Whether a meeting that ends at 10 and one that starts at 10 can share a room is a question to ask: the code treats them as not overlapping (ends[0] <= start).
Complexity, said out loud
Time: the sort is O(n log n) and dominates; the merge pass is O(n). The room count adds heap operations of O(log n) each, so O(n log n) overall. Space: O(n) for the output or the heap.
Ask the boundary question aloud: "do intervals that touch, like [1,4] and [4,5], overlap?" Whichever answer you are given changes <= to <. Interviewers plant this question deliberately.
Your turn: two practice problems
Try each on paper or in an editor first, with a timer set to 15 minutes. The solutions are hidden; each has tests in test_patterns.py that pass.
Return whether no two of the meetings overlap. [[7, 10], [2, 4]] is true; [[0, 30], [5, 10]] is false.
Signal to look for: "Any overlap?": sort by start, compare each meeting with the next.
Show a solution, with its tests
Step-by-step: what can_attend_all does, in plain English
- Sort by start.
- For each neighbouring pair, the first must end at or before the second starts.
- If every pair passes, the person can attend all.
# ── practice: can_attend_all ──
def can_attend_all(intervals):
s = sorted(intervals)
return all(s[i][1] <= s[i + 1][0] for i in range(len(s) - 1))
Time O(n log n), space O(n) for the sorted copy. Overlap anywhere means overlap between some neighbours once sorted, which is why we only compare neighbours.
Return the fewest intervals to remove so the rest do not overlap. [[1,2],[2,3],[3,4],[1,3]] gives 1.
Signal to look for: "Keep as many as possible": a greedy choice, and the sort key is the end time this time, not the start.
Show a solution, with its tests
Step-by-step: what min_removals does, in plain English
- Sort by end time.
- Keep an interval if it starts at or after the end of the last kept one.
- Otherwise it overlaps: count it as removed.
# ── practice: min_removals ──
def min_removals(intervals):
"""Fewest intervals to remove so the rest do not overlap (greedy: keep the earliest end)."""
removed = 0
last_end = float("-inf")
for start, end in sorted(intervals, key=lambda iv: iv[1]):
if start >= last_end:
last_end = end
else:
removed += 1
return removed
Time O(n log n). The reason to sort by end: choosing the interval that finishes earliest leaves the most room for the rest. Remember that the sort key changes with the question.
Quick reference — Intervals
- The signal
- "Meetings", "overlap", "merge", "rooms", "fewest to remove".
- First move
- Sort by start (or by end for "keep the most").
- Merge
- Overlaps the last merged one? stretch its end with
max; else start a new one. - Rooms
- Min-heap of end times; reuse the earliest-freeing room.
- Cost
- Time O(n log n) from the sort, space O(n).
- The question to ask
- Do touching intervals overlap?
06 · Week 3 · Pattern 12Dynamic Programming: Recursion, Then Memory, Then a Table
Dynamic programming is remembering the answers to small versions of a problem, so each is computed only once. Almost every DP solution is plain recursion plus a memory, optionally rewritten as a table.
Friday of week three, and the pattern Priya has dreaded most. Dynamic programming has a reputation as the hardest topic in coding rounds, and the reputation comes from skipping the first step. She will not start from a table. She starts from plain recursion that is slow but obviously correct, adds a memory with one decorator, and only then, if asked, converts it to a table. Three small steps instead of one leap.
Signals: the words in the problem that point here
Read the problem statement for these clues. Any two of them together is usually enough to name the pattern:
- "Fewest/most/minimum/maximum" of something, with a choice at every step
- "How many ways to…"
- "Longest common/increasing…" (two strings, or a list)
- The brute force is a recursion that tries every choice and asks the same smaller question again and again
- Overlapping sub-problems: the same small question appears repeatedly
dp_call_counts.py for coin change with coins 1, 2, 5. Log scale: each tick is 10 times more.- The red bars are plain recursion. From amount 10 to 25 the work grew from 544 to 1,627,441 calls: each extra 5 of amount multiplied the work by about 14. This is exponential growth, and it is why the first version feels fine on the example and times out in the interview.
- The blue bars are the same recursion with a memo (each sub-amount solved once). At amount 25 it makes 76 calls, about 21,000 times fewer, and the green table needs just 26 cells. The three versions give the same answers; only the repeated work is gone.
Fig. A3.29 measures the cost of not remembering. Plain recursion (red, marker 1) needs 544 calls at amount 10 and 1,627,441 at amount 25. The same recursion with a memory (blue, marker 2) needs 76. The answer is the same; only the repeated work is gone.
Why so many calls? Fig. A3.30 unrolls a tiny case, coins 1 and 2 and amount 4. It makes 12 calls for only 5 different amounts (marker 1), and the waste (marker 2) grows with the amount.
coin_change_recursive([1, 2], 4) as a tree of calls, coloured by amount.- Amount 2 (red) is solved twice, amount 1 (orange) three times and amount 0 (green) five times, each time re-solving the same small problem.
- Twelve calls for five different amounts. With bigger amounts the repeats multiply: that is the 1.6 million calls measured at amount 25.
- A memo (or a table) makes each amount a one-time job. The tree collapses to a single chain of five different amounts.
The test for dynamic programming is two properties. First, the answer to the big problem is built from answers to smaller versions of the same problem. Second, those smaller versions repeat. If only the first is true you have plain recursion; if both are true, remember the answers.
The recipe has four steps: say the sub-problem in a sentence ("the fewest coins to make amount a"), write the recursion, add the memory, and if needed write the table. Say the sentence aloud in the interview: it is half the answer.
The template: the shape to remember
Step-by-step: what the dynamic programming template does, in plain English
dp_templatemakes a listtablewith one cell per sub-problem size.- Set the base case by hand: the smallest sub-problem, whose answer you know.
- Fill the table from small to large; each cell is a rule applied to cells already filled.
- The rule here (add the two previous cells) is only an example; every DP problem has its own rule.
- The answer is one particular cell, usually the last.
# ── template: dynamic programming ──
def dp_template(n):
table = [0] * (n + 1) # table[i] = answer for the sub-problem of size i
table[0] = 1 # base case
for i in range(1, n + 1):
table[i] = table[i - 1] + (table[i - 2] if i >= 2 else 0) # rule: built from smaller answers
return table[n]
if __name__ == "__main__":
print(first_repeat([3, 1, 4, 1, 5]), pair_with_sum_sorted([1, 3, 5, 8], 11))
print(longest_window_at_most_k_distinct("eceba", 2), prefix_totals([1, 2, 3]))
print(next_greater([2, 1, 3]), first_true(0, 100, lambda v: v * v >= 50))
print(k_largest([5, 1, 9, 3], 2), sweep_intervals([[1, 3], [2, 4]]), dp_template(10))
The worked problem: Coin Change, Then Longest Common Subsequence
Problem 1. Given coin values and an amount, return the fewest coins that add up to the amount, or −1 if impossible. Coins [1, 2, 5], amount 11 gives 3 (5 + 5 + 1). Problem 2. Given two strings, return the length of their longest common subsequence: "abcde" and "ace" gives 3.
The ladder has four chunks: plain recursion, then memory, then a table (one dimension), then a grid (two dimensions). Each is a small edit of the one before. The three figures after this paragraph show the table form before you see the code for it.
coin_change([1, 2, 5], 11) filled left to right; each cell is the fewest coins for that amount.- Cell 11 looks back 5 cells to cell 6 (value 2) and adds one coin: 2 + 1 = 3. It also tries coins 1 and 2 (cells 10 and 9, both 2 and 3 coins away) and keeps the smallest, 3.
- The answer sits in the last cell: 3 coins (5 + 5 + 1). The table needed only 11 cells × 3 coins = 33 small steps.
- The base case. Cell 0 is 0 because making zero takes no coins, and every other cell is built from cells to its left. Fill order matters: when we reach 11, 6 is already done.
Now the same idea as a table. Filled from the smallest amount upward, every cell looks only at cells already filled. Fig. A3.31 shows the table for amount 11. Cell 11 looks back five cells to cell 6, adds one coin of 5 (marker 1), and gets 3. The answer sits in the last cell (marker 2).
"abcde" and "ace": the grid lcs_length fills.- Each cell answers a smaller version of the question: the best common subsequence of the first i letters of one word and the first j letters of the other. The edge row and column are 0 because an empty word shares nothing.
- The bottom-right cell answers the whole question: 3, the subsequence "ace". It was reached by three diagonal steps from the corner.
- When the two letters match, the cell is its diagonal neighbour plus 1. When they differ, it is the larger of the cell above and the cell to the left: we drop one letter from one word and keep the better result.
Some problems have two things changing at once, such as two strings. Then the table has two dimensions: one row per prefix of the first string and one column per prefix of the second. Fig. A3.32 is that grid for the longest common subsequence (letters that appear in both words in the same order, not necessarily next to each other) of "abcde" and "ace". The corner cell (marker 2) answers the whole question.
A word on what the memo remembers. For coin_change_memo([1, 2, 5], 5) the cache after the call is {1: 1, 2: 1, 3: 2, 4: 2, 5: 1}: for each amount, the fewest coins. Each entry is computed once and then reused. The numbers come from followup_numbers.py.
Build it in chunks
We build p12_dynamic_programming.py in four chunks: the recursion, the memory, the table, and the two-dimensional grid.
-
Chunk 1 — plain recursion: the fewest coins that make an amount
Slow, but obviously correct and easy to write, so it is the right first step. It also defines the sub-problem: the fewest coins for a smaller amount.
Step-by-step: what chunk 1 does, in plain English
- An amount of 0 needs 0 coins; a negative amount is impossible (−1).
- For every coin, ask the same question for the amount left after using that coin.
- Ignore answers of −1 (impossible).
- Keep the best result plus one for the coin just used.
- The main block tries 11 with coins 1, 2, 5, and 3 with only coin 2 (impossible).
p12_dynamic_programming.py — chunk 1runs offlinefrom functools import lru_cache # ── chunk 1: plain recursion - the fewest coins that make an amount ── def coin_change_recursive(coins, amount): if amount == 0: return 0 if amount < 0: return -1 best = -1 for c in coins: sub = coin_change_recursive(coins, amount - c) if sub >= 0 and (best < 0 or sub + 1 < best): best = sub + 1 return best if __name__ == "__main__": print(coin_change_recursive([1, 2, 5], 11), coin_change_recursive([2], 3))A function that calls itself with a smaller argument; −1 as a "no answer" marker.
Run
python3 p12_dynamic_programming.py. It prints3 -1.terminalactual output (this chunk adds)3 -1 -
Chunk 2 — add memory: remember each sub-answer
The recursion asks about the same amounts repeatedly. One decorator,
lru_cache, remembers each result so each amount is solved once.Step-by-step: what chunk 2 does, in plain English
- The inner function
gois the recursion from chunk 1, with the same base cases. @lru_cache(maxsize=None)stores the result for each argument and returns the stored result on repeat calls.- Collect the answers for each coin, add one for the coin used, and take the smallest (or −1 if none).
- The main block also solves amount 200, which the plain version could not finish.
p12_dynamic_programming.py — chunk 2runs offline# ── chunk 2: memoise - remember each sub-answer ── def coin_change_memo(coins, amount): @lru_cache(maxsize=None) def go(rest): if rest == 0: return 0 if rest < 0: return -1 options = [go(rest - c) for c in coins] options = [o + 1 for o in options if o >= 0] return min(options) if options else -1 return go(amount) if __name__ == "__main__": print(coin_change_memo([1, 2, 5], 11), coin_change_memo([1, 2, 5], 200))functools.lru_cache— an automatic memory for a function's results; this is called memoisation.Run
python3 p12_dynamic_programming.pywith chunks 1 to 2 in the file. It prints3 40from the memoised version of amount 11 and then amount 200.terminalactual output (this chunk adds)3 40 - The inner function
-
Chunk 3 — a table filled from small amounts upward
The memo version has the right shape. A table does the same work without recursion, so there is no recursion limit and the order of work is visible.
Step-by-step: what chunk 3 does, in plain English
INFis bigger than any real answer; it stands for "not reachable yet".table[a]is the fewest coins for amount a; amount 0 is 0.- For each amount from 1 up, try each coin that fits and take the best
table[a - c] + 1. - Return the last cell, or −1 if it is still INF.
- The main block prints three answers.
p12_dynamic_programming.py — chunk 3runs offline# ── chunk 3: a table, filled from small amounts upward ── def coin_change(coins, amount): INF = amount + 1 # bigger than any real answer table = [0] + [INF] * amount # table[a] = fewest coins to make amount a for a in range(1, amount + 1): for c in coins: if c <= a: table[a] = min(table[a], table[a - c] + 1) return table[amount] if table[amount] != INF else -1 if __name__ == "__main__": print(coin_change([1, 2, 5], 11), coin_change([2], 3), coin_change([1, 2, 5], 200))Filling a list from the base case upward; the recursion's "ask a smaller amount" becomes "look back in the table".
Run
python3 p12_dynamic_programming.pywith chunks 1 to 3 in the file. It prints3 -1 40for amount 11, amount 3 with coin 2, and amount 200.terminalactual output (this chunk adds)3 -1 40 -
Chunk 4 — two dimensions: longest common subsequence of two strings
Same recipe, a grid instead of a list: one axis per string. The cell rule is the only new thinking.
Step-by-step: what chunk 4 does, in plain English
grid[i][j]is the answer for the first i letters of a and the first j letters of b; row 0 and column 0 stay 0.- Loop over every cell.
- If the two letters match, extend the diagonal:
grid[i-1][j-1] + 1. - If not, take the better of dropping a letter from one side or the other: the larger of the cell above and the cell to the left.
- Return the corner cell.
p12_dynamic_programming.py — chunk 4runs offline# ── chunk 4: two dimensions - longest common subsequence of two strings ── def lcs_length(a, b): # grid[i][j] = LCS length of the first i letters of a and the first j letters of b grid = [[0] * (len(b) + 1) for _ in range(len(a) + 1)] for i in range(1, len(a) + 1): for j in range(1, len(b) + 1): if a[i - 1] == b[j - 1]: grid[i][j] = grid[i - 1][j - 1] + 1 # letters match: extend the diagonal else: grid[i][j] = max(grid[i - 1][j], grid[i][j - 1]) # skip a letter from one side return grid[len(a)][len(b)] if __name__ == "__main__": print(lcs_length("abcde", "ace"), lcs_length("abc", "xyz"))A list of lists as a grid;
[[0] * (m + 1) for _ in range(n + 1)]builds it (do not write[[0] * m] * n, which shares one row).Run
python3 p12_dynamic_programming.pywith chunks 1 to 4 in the file. It prints3 0: "abcde" and "ace" share 3 letters in order; "abc" and "xyz" share none.terminalactual output (this chunk adds)3 0
The whole program
Lines 5–22 are chunk 1, 23–40 are chunk 2, 41–55 are chunk 3, 56–70 are chunk 4. Every chunk starts with a # ── chunk n ── comment. This file lives at code/a3-dsa-reset/p12_dynamic_programming.py, with its tests in test_patterns.py.
# Pattern 12 - dynamic programming: recursion -> memo -> table. Python 3.12.
from functools import lru_cache
# ── chunk 1: plain recursion - the fewest coins that make an amount ──
def coin_change_recursive(coins, amount):
if amount == 0:
return 0
if amount < 0:
return -1
best = -1
for c in coins:
sub = coin_change_recursive(coins, amount - c)
if sub >= 0 and (best < 0 or sub + 1 < best):
best = sub + 1
return best
if __name__ == "__main__":
print(coin_change_recursive([1, 2, 5], 11), coin_change_recursive([2], 3))
# ── chunk 2: memoise - remember each sub-answer ──
def coin_change_memo(coins, amount):
@lru_cache(maxsize=None)
def go(rest):
if rest == 0:
return 0
if rest < 0:
return -1
options = [go(rest - c) for c in coins]
options = [o + 1 for o in options if o >= 0]
return min(options) if options else -1
return go(amount)
if __name__ == "__main__":
print(coin_change_memo([1, 2, 5], 11), coin_change_memo([1, 2, 5], 200))
# ── chunk 3: a table, filled from small amounts upward ──
def coin_change(coins, amount):
INF = amount + 1 # bigger than any real answer
table = [0] + [INF] * amount # table[a] = fewest coins to make amount a
for a in range(1, amount + 1):
for c in coins:
if c <= a:
table[a] = min(table[a], table[a - c] + 1)
return table[amount] if table[amount] != INF else -1
if __name__ == "__main__":
print(coin_change([1, 2, 5], 11), coin_change([2], 3), coin_change([1, 2, 5], 200))
# ── chunk 4: two dimensions - longest common subsequence of two strings ──
def lcs_length(a, b):
# grid[i][j] = LCS length of the first i letters of a and the first j letters of b
grid = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
grid[i][j] = grid[i - 1][j - 1] + 1 # letters match: extend the diagonal
else:
grid[i][j] = max(grid[i - 1][j], grid[i][j - 1]) # skip a letter from one side
return grid[len(a)][len(b)]
if __name__ == "__main__":
print(lcs_length("abcde", "ace"), lcs_length("abc", "xyz"))
3 -1
3 40
3 -1 40
3 0
Read the output. Chunks 1 to 3 give the same answers; chunk 2 is the first that can do amount 200 (answer 40, forty coins of 5). The plain recursion at amount 200 would never finish: its call count multiplies about 14 times for every 5 added to the amount. The figure gives the scale.
Complexity, said out loud
Coin change. Time O(amount × number of coins), space O(amount). LCS. Time O(len(a) × len(b)), space the same for the grid. The general rule: the time is (number of sub-problems) × (work per sub-problem).
The interview-safe order is: say the sub-problem, write the recursion, add lru_cache, run the tests, and only convert to a table if asked or if depth might exceed 1,000. Memoised recursion and a table are the same algorithm in a different order.
Your turn: two practice problems
Try each on paper or in an editor first, with a timer set to 15 minutes. The solutions are hidden; each has tests in test_patterns.py that pass.
Houses in a row hold some money each. You cannot rob two neighbouring houses. Return the most you can take: [2, 7, 9, 3, 1] gives 12 (houses 1, 3 and 5).
Signal to look for: A choice at every step (take it or skip it) and the best total builds from earlier best totals.
Show a solution, with its tests
Step-by-step: what house_robber does, in plain English
takeis the best total if we rob the previous house;skipif we do not.- For each house: robbing it means we skipped the previous, so the new
takeis the oldskipplus this house's money. - Skipping it leaves the better of the two old values.
- At the end, the better of the two is the answer.
# ── practice: house_robber ──
def house_robber(money):
take, skip = 0, 0 # best total if we rob / do not rob the previous house
for m in money:
take, skip = skip + m, max(take, skip)
return max(take, skip)
Time O(n), space O(1): only the last two states are needed, so the table collapses to two variables. This shrinking of a table to the few cells that are still needed is a common follow-up.
Return the fewest single-letter edits (insert, delete, replace) to turn one word into another. "horse" to "ros" is 3.
Signal to look for: Two strings: a grid with one axis per word; the cell rule has three moves.
Show a solution, with its tests
Step-by-step: what edit_distance does, in plain English
prevholds the previous row: the distance from the empty string to each prefix of b.- For each letter of a, build a new row
curwhose first cell is i (delete i letters). - If the letters match, the cell copies the diagonal; otherwise it is 1 plus the cheapest of delete, insert and replace.
- Replace
prevwithcurand continue; the last cell of the last row is the answer.
# ── practice: edit_distance ──
def edit_distance(a, b):
prev = list(range(len(b) + 1)) # distance from "" to each prefix of b
for i in range(1, len(a) + 1):
cur = [i] + [0] * len(b)
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
cur[j] = prev[j - 1]
else:
cur[j] = 1 + min(prev[j], cur[j - 1], prev[j - 1]) # delete, insert, replace
prev = cur
return prev[len(b)]
Time O(len(a) × len(b)), space O(len(b)) because we keep only two rows. It is the same grid as LCS with one more option in the cell rule.
Quick reference — Dynamic programming
- The signal
- "Fewest/most", "how many ways", "longest common…", choices at every step, repeated sub-problems.
- The recipe
- Say the sub-problem; write the recursion; add
lru_cache; (optionally) write the table. - 1-D table
table[a]built fromtable[a − c]; base case by hand.- 2-D grid
- One axis per input; match extends the diagonal, mismatch takes the best neighbour.
- Cost
- Time = (number of sub-problems) × (work each); space = table size, often shrinkable to one or two rows.
07 · Week 4 · The 45-minute roundThe Round Script: What to Say at Each Step
The coding round is graded on how you work as much as on the code. A fixed seven-step script, with a sentence to say at each step, turns a frightening hour into a routine.
Week four begins. Priya now has twelve patterns, and still fears the hour itself: a stranger, a shared editor, silence. Her mock interviews showed the real problem. She knew the answers but typed in silence for twenty minutes, then ran out of time to test. So the plan changes from learning to performing: a script with a sentence at every step, and a clock that tells her where she should be.
timed_round.py.- The first 13 minutes are spent without writing any code: clarifying, doing examples by hand, saying the brute force, and finding the better idea. Candidates who start typing at minute 2 usually solve the wrong problem.
- Coding gets the biggest block, 21 minutes, but it ends at about minute 35. A solution that is typed but never run is a guess.
- The last 10 minutes are tests and wrap-up. This is where a nervous candidate skips ahead; a calm one traces an example and states the complexity.
Fig. A3.33 divides the 45 minutes. The first 13 minutes (marker 1) contain no code at all. Coding gets the biggest block (marker 2), and the last ten minutes are for tests and wrap-up (marker 3). The marks are the ones timed_round.py prints.
| # | Step | What you do | What you say (example) | Minutes |
|---|---|---|---|---|
| 1 | Clarify | Restate the problem. Ask about input size, duplicates, negatives, empty input, and what to return when there is no answer. | "So I get a list of integers, possibly empty, and return the indices of a pair that sums to the target. Can numbers repeat? What if no pair exists?" | 0 to 3 |
| 2 | Examples | Write two examples by hand, one normal and one edge case. These become your tests. | "Take [2, 7, 11, 15] with target 9: the answer is [0, 1]. Edge case: [3, 3] with target 6 should return [0, 1]." | 3 to 7 |
| 3 | Brute force | Say the obvious solution and its cost. Do not code it. | "The simple way is to check every pair: O(n²) time, O(1) space. It works but is slow for large inputs." | 7 to 10 |
| 4 | Optimise | Name the pattern, say the idea in one sentence, say the new cost. Get a nod before coding. | "This is a hashing problem: for each number I need its partner, and a dict tells me in O(1) if I have seen it. That gives O(n) time, O(n) space. Shall I go ahead?" | 10 to 13 |
| 5 | Code | Write it cleanly with real names. Talk through each block as you write it. Stay in the language; do not pseudo-code. | "I will loop with enumerate, compute need = target − x, check the dict first and store after, so a number cannot pair with itself." | 13 to 35 |
| 6 | Test | Trace one example by hand, then the edge cases from step 2, then empty input. Fix what you find, out loud. | "Running [3, 3]: first 3 is stored, second 3 finds need = 3 at index 0, returns [0, 1]. Now the empty list: loop never runs, returns []." | 35 to 41 |
| 7 | Wrap up | State final time and space. Say what you would improve with more time. | "O(n) time, O(n) space. With more time I would add input validation, and for a sorted input I would switch to two pointers to save the memory." | 41 to 45 |
Two rules sit under the table. Never code before step 4 is agreed. A nod from the interviewer is worth more than five minutes of typing, because it means you are about to write the right thing. Never stay silent for more than about thirty seconds. If you are thinking, say "I am checking whether a heap would help here". The interviewer cannot grade thinking they cannot hear.
Clarify the question.
Do two examples, by hand.
Say the brute force and its cost.
Name the pattern, then code.
Test, then say the complexity.
Each line is one block of the timeline in the figure: clarify and examples fill the first 7 minutes, brute force and pattern naming reach minute 13, coding runs to 35, tests and complexity fill the end.
Tonight's talk: the Brute Force and the Optimised Solution argue over "Who gets you the job?"
I always work. In the pair-sum problem I check all 7,998,000 pairs of 4,000 numbers and I never get it wrong. Say what you like about me, nobody has failed a round with a correct answer.
In plain words: the brute force is slow but correct. At n = 4,000 it makes 7,998,000 comparisons and took 232 ms in the measurement above.
You took 232 milliseconds for 4,000 numbers. For a million you would take hours. I need one pass and a dict, and I handle a million numbers in about a second. The interviewer asked "can you do better?" because I exist.
In plain words: the optimised version trades memory (a dict) for time, one pass instead of a loop inside a loop.
You are also where the bugs live. Your "store after you check" line, your >= left test, your {0: 1} start: every one has caught candidates who never tested. I am the thing that checks you.
In plain words: the optimised code is harder to get right, and the brute force is what you test it against (as in the random tests in each ladder).
True, and I will not pretend otherwise. Also true: if you say me first, and only then you, the interviewer sees someone who reasons. We should not be rivals. We will see who they pick when the input has ten items.
In plain words: say the brute force first, then improve it, but for tiny inputs the simple version is a fine answer.
Before reading on: you are 20 minutes in, you can only think of the brute force, and the interviewer is quiet. What do you do?
Reveal the answer
Code the brute force. A correct, tested O(n²) answer scores better than a half-finished O(n) one. Say aloud: "I will get the simple version working first and then look for the repeated work." Then name the repeated work (what is being scanned again and again?) and ask whether a dict, a sort, a pointer or a heap removes it. Candidates who do this often reach the better answer, and the ones who do not still finish with working code.
Here is the timing tool for rehearsal. It prints the minute marks for the round, waits for you to press Enter when you finish, and tells you how long you took. Use a small minutes value (like 1) just to see it work.
Step-by-step: what timed_round.py does, in plain English
SCRIPTlists each step with the fraction of the round at which it should begin.mainreads the problem name and the minutes from the command line (45 by default).- It prints each step's start minute, scaled to the length of the round.
- It starts a stopwatch, then waits for you to press Enter.
- It reports how many minutes you used and whether you were inside the limit.
# A 45-minute mock round with a visible clock.
# Run: python3 timed_round.py p05_stack.days_until_warmer 45
# It prints the minute marks of the round script, then waits for Enter when you finish
# and reports how long you took. (Use a small minutes value, e.g. 1, to try it.)
import sys
import time
SCRIPT = [("clarify the problem and the inputs", 0.00),
("walk through 2 examples (include an edge case)", 0.07),
("say the brute force and its complexity", 0.15),
("find and say the better idea", 0.22),
("code it", 0.30),
("test with the examples, then edge cases", 0.78),
("state final complexity and next improvements", 0.92)]
def main():
name = sys.argv[1] if len(sys.argv) > 1 else "a problem"
minutes = float(sys.argv[2]) if len(sys.argv) > 2 else 45
print(f"Round on {name}: {minutes:g} minutes")
for step, frac in SCRIPT:
print(f" minute {frac * minutes:5.1f} {step}")
start = time.perf_counter()
input("Press Enter when you have finished... ")
used = (time.perf_counter() - start) / 60
verdict = "inside" if used <= minutes else "over"
print(f"you used {used:.2f} of {minutes:g} minutes ({verdict} the limit)")
if __name__ == "__main__":
main()
Round on p05_stack.days_until_warmer: 45 minutes
minute 0.0 clarify the problem and the inputs
minute 3.2 walk through 2 examples (include an edge case)
minute 6.8 say the brute force and its complexity
minute 9.9 find and say the better idea
minute 13.5 code it
minute 35.1 test with the examples, then edge cases
minute 41.4 state final complexity and next improvements
Press Enter when you have finished...
you used 0.00 of 45 minutes (inside the limit)
Quick reference — The round script
- Seven steps
- Clarify, examples, brute force, optimise, code, test, wrap up.
- Before minute 13
- No code: clarify, two examples, brute force, the better idea.
- Name the pattern
- "This is a sliding window problem because the answer is a contiguous stretch with a rule."
- Never silent
- Narrate: what you are checking and why.
- Finish by minute 35
- Leave ten minutes to trace examples and state the complexity.
- Stuck
- Code the brute force; a tested slow answer beats a half-written fast one.
08 · Week 4 · The AI-assisted roundThe AI-Assisted Coding Round: Driving, Not Riding
In an AI-assisted round you are given an AI assistant and judged on how you use it. The code matters less than whether you steer the AI, check what it writes, and can explain it.
Round three of Priya's loop is the new kind, and she has less practice at it than at the classic round. She uses an AI coder daily at work, so she assumes it will be easy. Her first mock showed the trap: she pasted the problem, accepted the answer and had nothing to say when the interviewer asked about an edge case. The skill being graded is not typing. It is judgement.
This section covers only the round. For how the AI-enabled interview round fits into the whole loop, read Module 17. For the daily workflow, how to write specifications and review AI output at work, see Module 15.
- You speak first. State the pattern and the approach in two sentences before typing a prompt. A prompt that says "solve this" shows nothing; a prompt that says "use a monotonic stack, return indexes" shows judgment.
- The AI writes the first draft quickly. That speed is the reason the round exists, and it is also the risk: a fluent answer can be wrong in an edge case.
- You run tests you wrote or reviewed, including the empty input and the duplicate case. This is the step interviewers watch hardest.
- You read every line you keep and can explain it. If you cannot explain a line, delete it or ask for a simpler one.
Fig. A3.34 is the loop. You state the plan first (marker 1), the AI drafts (marker 2), you run your own tests (marker 3), and you read and explain what you keep (marker 4). A failing test sends you back to step 1 with a better prompt.
| What is graded | Strong looks like | Weak looks like |
|---|---|---|
| Problem decomposition | Breaks the task into pieces and asks for one piece at a time | Pastes the whole task and accepts the whole answer |
| Prompt quality | Names the pattern, the input shape, the edge cases and the return type | "Solve this" |
| Verification | Writes or reads tests first and runs them; checks empty, one item, duplicates | Reads the code, says "looks right", moves on |
| Understanding | Explains any line on request, spots the bug in a plausible draft | Cannot say why a line is there |
| Judgement about the AI | Rejects a draft that is too complex; asks for a simpler one; fixes small things by hand | Argues with the AI for ten minutes over a one-line fix |
| Communication | Narrates what and why throughout | Silent while the AI works |
How to drive: four prompts that work
- State the pattern first. "This looks like a sliding window with a last-seen dict. Write
longest_unique(s)returning an int; the empty string returns 0." - Ask for tests before code. "List five test cases including an empty string and a string where the repeat is outside the window."
- Ask for a reason. "Why does the left edge only move forward?" If the answer is vague, the code may be too.
- Constrain it. "Keep it under 15 lines and O(n) time, no regular expressions."
The cheapest way to learn to verify is to watch an AI-style draft fail. The program below holds a draft that is a very common near-miss for the sliding-window problem. It passes the obvious example and fails on "abba". Read the draft first and see if you can spot the problem before you look at the output.
Step-by-step: what ai_draft_check.py does, in plain English
draft_longest_uniqueis the "AI draft": it moves the left edge whenever the letter was seen before, whether or not the earlier copy is still inside the window.checked_longest_uniqueis the same function after review, with the extraand last_seen[ch] >= leftcheck.MY_TESTSholds your own test inputs with the expected answers, written from the problem statement, not from the AI's code.- The main block runs both functions over all tests and prints ok or FAIL per input.
# What to do with an AI-written draft: run it against your OWN tests before you trust it.
# The "draft" below is the kind of fluent, almost-right code an assistant produces.
def draft_longest_unique(s):
last_seen = {}
left = best = 0
for right, ch in enumerate(s):
if ch in last_seen: # BUG: forgets "and the earlier copy is inside the window"
left = last_seen[ch] + 1
last_seen[ch] = right
best = max(best, right - left + 1)
return best
def checked_longest_unique(s):
last_seen = {}
left = best = 0
for right, ch in enumerate(s):
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1
last_seen[ch] = right
best = max(best, right - left + 1)
return best
MY_TESTS = [("abcabcbb", 3), ("bbbbb", 1), ("", 0), ("pwwkew", 3), ("abba", 2)]
if __name__ == "__main__":
for name, fn in (("AI draft", draft_longest_unique), ("after review", checked_longest_unique)):
print(name)
for text, want in MY_TESTS:
got = fn(text)
print(f" {text!r:12} want {want} got {got} {'ok' if got == want else 'FAIL'}")
AI draft
'abcabcbb' want 3 got 3 ok
'bbbbb' want 1 got 1 ok
'' want 0 got 0 ok
'pwwkew' want 3 got 3 ok
'abba' want 2 got 3 FAIL
after review
'abcabcbb' want 3 got 3 ok
'bbbbb' want 1 got 1 ok
'' want 0 got 0 ok
'pwwkew' want 3 got 3 ok
'abba' want 2 got 2 ok
Read the output. The draft passes four of five tests. It only fails on "abba": when the second a arrives, the earlier a is already outside the window, but the draft still jumps the left edge back to it, so the window grows wrongly to length 3. A candidate who ran only the obvious example would have shipped it. A fifth test, chosen because of what you know about the pattern, caught it. That is verification, and that is what is graded.
"If the AI writes the code anyway, why am I grinding DSA at all?"
— Priya, at 1 a.m., in week two
Because you cannot steer or check what you do not understand. The AI draft above looked right and was wrong, and only a person who knew what the left edge is for could see why. Recognising the pattern is what lets you say "use a sliding window" in the first place, and judging the draft is what lets you reject a bad one.
The honest part: the weight of the classic round is shifting. Some employers now run only the AI-assisted kind, and the pure puzzle rounds may shrink. Even so, the loop that Priya faces has both, and the AI round rewards exactly the pattern knowledge you are building here.
Quick reference — The AI-assisted round
- What is graded
- Decomposition, prompts, verification, understanding, judgement, communication.
- Drive
- Say the plan first, ask for one piece at a time, name the pattern and edge cases in the prompt.
- Verify
- Your own tests first: empty, one item, duplicates, the case that breaks the pattern's rule.
- Own it
- Delete or simplify any line you cannot explain.
- Time
- Spend at least a third of the round running tests and reading code.
09 · The four-week planThe Four-Week Reset Plan
A schedule beats willpower. Here is the whole plan on one table: one pattern a day, a review day each week, and timed mocks from week two on.
Priya has now seen every piece, so she writes her calendar. She works full-time, so the plan is about 90 minutes on weekdays and three hours on one weekend day. Each weekday is one pattern: read its section, solve its two practice problems with a 15-minute timer, then re-solve the worked problem from a blank file the next day.
| Week | Days | Focus | What to do | Done when |
|---|---|---|---|---|
| Weekend 0 | Sat and Sun | Big-O, the toolbox | Run bigo_timing.py and toolkit_costs.py; do the pencil exercises; say the cost table aloud | You can state the cost of 8 built-in operations without looking |
| 1 | Mon to Thu | Hashing, two pointers, sliding window, prefix sums | One pattern per day: worked problem from blank, then two practice problems timed at 15 minutes | 8 practice problems solved with tests passing |
| 1 | Fri · Sat | Review and Mock 1 | Redo the two you missed. Mock 1: timed_round.py, 45 minutes, one problem from weeks one topics, speak aloud | You finished inside 45 minutes, or you know where you lost time |
| 2 | Mon to Thu | Stack, binary search, linked list, trees | Same routine | 8 more practice problems solved |
| 2 | Fri · Sat | Review and Mock 2 | Mock 2: a problem from week 2, then log it in mock_tracker.py | The tracker names a weakest pattern |
| 3 | Mon to Wed · Fri | Graphs, heaps, intervals, dynamic programming | Same routine; Thursday is a catch-up day on your weakest pattern | 8 more practice problems solved |
| 3 | Sat | Mock 3 | A mixed problem, no pattern named in advance; use the recognition drill first | You named the pattern before coding |
| 4 | Mon | The round script | Read the script; rehearse the seven steps on a problem you already know | You can say the steps without notes |
| 4 | Tue | The AI-assisted round | Practise with an AI assistant on two problems; write your own tests first | You caught at least one wrong draft |
| 4 | Wed to Fri | Three timed mocks | One classic round and one AI-assisted round, plus one on your weakest pattern | Three logged rounds; no pattern below 70% solved |
| 4 | Weekend | Rest | Light review of the quick references only | You are rested |
- Each weekday of weeks 1 to 3 is one pattern, in the order of the sections above. Friday and Saturday are review and a timed mock: the mock is where the freeze is practised away.
- Saturday is the mock day in every week; week 4 puts three mocks at the end, one classic, one AI-assisted and one on your weakest pattern.
Fig. A3.35 is the same plan as a calendar. Each weekday of the first three weeks is one pattern (marker 1), and Saturday is a timed mock (marker 2).
Two choices in the plan are deliberate. Patterns are taught in order of how often they appear and how much they build on each other: hashing before prefix sums, sliding window before intervals. And every weekday ends with re-solving yesterday's worked problem from a blank file, because reading a solution feels like knowing it and is not the same.
10 · Recognition drillThirty Problems, One Question: Which Pattern?
This drill trains the one skill that decides whether you freeze: reading a one-line problem and naming the pattern before thinking about code.
On the Saturday before each mock, Priya runs a drill with no code at all: thirty one-line problem statements, and for each she says only the pattern and the reason. She covers the answer with her hand. When she can name twenty-five in under two minutes each, she feels the freeze loosen, because she now has a first move for almost any problem.
Cover the right column, read the statement, say the pattern aloud, then open the row to check. The reason in each answer is the signal you should have noticed; that is what to practise, not the label.
| # | Problem statement | Your answer |
|---|---|---|
| 1 | Find two numbers in an array that add up to a target. | Show the patternhashing — need a partner: a dict answers 'have I seen it?' in O(1) |
| 2 | Group words that are anagrams of each other. | Show the patternhashing — a sorted-letters key puts anagrams in the same bucket |
| 3 | Count how many times each word appears and report the most common. | Show the patternhashing — counting is a Counter |
| 4 | Is there any duplicate in this list? | Show the patternhashing — a set remembers what you have seen |
| 5 | In a sorted array, find a pair that sums to a target. | Show the patterntwo pointers — sorted + pair = one pointer at each end |
| 6 | Check whether a string is a palindrome, ignoring punctuation. | Show the patterntwo pointers — compare from both ends inward |
| 7 | Remove duplicates from a sorted array in place. | Show the patterntwo pointers — a read pointer and a write pointer |
| 8 | Find the longest substring without repeating characters. | Show the patternsliding window — 'longest stretch' with a rule that can break |
| 9 | Largest sum of any 5 consecutive days. | Show the patternsliding window — fixed-size window: add one, drop one |
| 10 | Smallest subarray whose sum is at least 100. | Show the patternsliding window — 'smallest stretch' of positive numbers: grow then shrink |
| 11 | How many subarrays add up to exactly k? | Show the patternprefix sums — a running total plus a dict of totals seen |
| 12 | Answer 100,000 queries: sum of the items between index i and j. | Show the patternprefix sums — many range sums: precompute totals once |
| 13 | For each day, how many days until a warmer one? | Show the patternmonotonic stack — 'next greater element' |
| 14 | Do the brackets in this string match up? | Show the patternstack — last opened is first closed |
| 15 | Evaluate a reverse-polish arithmetic expression. | Show the patternstack — operands wait on a stack for their operator |
| 16 | Find a target in a sorted array. | Show the patternbinary search — sorted + find = halve the range |
| 17 | Smallest ship capacity that delivers all packages in D days. | Show the patternbinary search on the answer — 'smallest value that works', and 'works' is monotonic |
| 18 | Find the smallest number in a rotated sorted array. | Show the patternbinary search — one half is always still sorted |
| 19 | Reverse a linked list. | Show the patternlinked list — flip one arrow at a time with prev/cur/next |
| 20 | Does this linked list contain a cycle? | Show the patternlinked list — fast and slow pointers meet inside a loop |
| 21 | Find the middle node of a linked list in one pass. | Show the patternlinked list — fast moves two for every one of slow |
| 22 | Maximum depth of a binary tree. | Show the patterntrees — 1 + the deeper child: recursion |
| 23 | Print a tree level by level. | Show the patterntrees (BFS) — a queue, one level at a time |
| 24 | Fewest moves from the top-left to the bottom-right of a maze. | Show the patterngraphs (BFS) — 'fewest steps' on an unweighted graph is BFS |
| 25 | Count the islands in a grid of land and water. | Show the patterngraphs (DFS) — flood fill each unseen piece of land |
| 26 | Can all courses be finished, given prerequisite pairs? | Show the patterngraphs (topological sort) — 'order with dependencies' / cycle check |
| 27 | The k most frequent elements. | Show the patternheaps — 'top k' = a heap of size k |
| 28 | Merge k sorted lists into one sorted list. | Show the patternheaps — the heap always holds each list's current smallest |
| 29 | Merge all overlapping meetings. | Show the patternintervals — sort by start; overlaps become neighbours |
| 30 | Fewest coins that make an amount. | Show the patterndynamic programming — 'fewest/most/how many ways' with overlapping sub-problems |
The same list is in drill_data.py, and drill.py quizzes you on five random ones in the terminal. It is short enough to read in full:
Step-by-step: what drill.py does, in plain English
- It imports the thirty rows from
drill_data.py. - With
--list, it prints every statement with its answer and reason. - Otherwise it picks five at random with
random.sample. - For each, it asks for the pattern with
input(), and counts the answer as right if what you typed appears in the answer text. - It prints "right" or the correct answer with its reason, and a final score out of five.
# Quiz yourself: python3 drill.py (asks 5 random statements, you type the pattern)
# python3 drill.py --list (prints all 30 with answers)
import random
import sys
from drill_data import DRILL
def main():
if "--list" in sys.argv:
for i, (q, pattern, why) in enumerate(DRILL, 1):
print(f"{i:2}. {q}\n -> {pattern} ({why})")
return
score = 0
picked = random.sample(DRILL, 5)
for q, pattern, why in picked:
guess = input(f"\n{q}\npattern? ").strip().lower()
right = guess != "" and (guess in pattern or pattern.split()[0] in guess)
score += right
print(("right: " if right else "answer: ") + f"{pattern} - {why}")
print(f"\n{score}/5")
if __name__ == "__main__":
main()
11 · The labLab: Three Timed Mocks and a Tracker
With four weeks gone, Priya has one more tool to build, and it is for her, not for an interviewer: a tiny tracker that tells her what to practise tomorrow, so the last days are spent on her weakest pattern, not her favourite.
Build it in chunks
We build mock_tracker.py in three chunks. Each runs on its own; the whole file follows.
-
Chunk 1 — record one mock round
The tracker begins with the smallest useful thing: a list of rounds, each with a pattern, the minutes taken, and whether it was solved.
Step-by-step: what chunk 1 does, in plain English
LOGis a list of dicts, one per round.recordappends a round with its pattern, minutes and result.- The main block records three sample rounds and prints how many are logged.
mock_tracker.py — chunk 1runs offlinefrom collections import defaultdict # ── chunk 1: record one mock round ── LOG = [] def record(pattern, minutes, solved): LOG.append({"pattern": pattern, "minutes": minutes, "solved": solved}) if __name__ == "__main__": record("sliding window", 38, True) record("graphs", 45, False) record("sliding window", 29, True) print(len(LOG), "rounds logged")A list of dicts as a tiny database.
Run
python3 mock_tracker.py. It prints how many rounds are logged.terminalactual output (this chunk adds)3 rounds logged -
Chunk 2 — summarise by pattern
A log is only useful if it answers "where am I weak?". Grouping by pattern gives rounds, solve rate and average time for each.
Step-by-step: what chunk 2 does, in plain English
defaultdict(list)gathers the rounds of each pattern.- For each pattern, count its rounds, work out the percentage solved, and the average minutes.
- The main block prints one line per pattern.
mock_tracker.py — chunk 2runs offline# ── chunk 2: summarise by pattern ── def summary(log): groups = defaultdict(list) for row in log: groups[row["pattern"]].append(row) out = {} for pattern, rows in groups.items(): out[pattern] = { "rounds": len(rows), "solved_pct": round(100 * sum(r["solved"] for r in rows) / len(rows)), "avg_minutes": round(sum(r["minutes"] for r in rows) / len(rows), 1), } return out if __name__ == "__main__": for pattern, s in summary(LOG).items(): print(f"{pattern:15} {s['rounds']} rounds, {s['solved_pct']}% solved, {s['avg_minutes']} min average")Grouping with
defaultdict(list);sumover a list of booleans counts the True values.Run
python3 mock_tracker.pywith chunks 1 to 2 in the file. It prints one line per pattern after the first line.terminalactual output (this chunk adds)sliding window 2 rounds, 100% solved, 33.5 min average graphs 1 rounds, 0% solved, 45.0 min average -
Chunk 3 — pick the pattern to practise next
The decision rule: lowest solve rate first, and for equal rates, the slower pattern.
Step-by-step: what chunk 3 does, in plain English
- Build the summary.
- If there is nothing logged, return None.
minwith a key chooses the pattern with the lowest solve rate; the minus sign on average minutes breaks ties in favour of the slower one.- The main block prints the pattern to practise next.
mock_tracker.py — chunk 3runs offline# ── chunk 3: pick the pattern to practise next ── def weakest(log): """Lowest solve rate first; ties go to the slower pattern. None if the log is empty.""" s = summary(log) if not s: return None return min(s, key=lambda p: (s[p]["solved_pct"], -s[p]["avg_minutes"])) if __name__ == "__main__": print("practise next:", weakest(LOG))min(..., key=...)with a tuple key for tie-breaking.Run
python3 mock_tracker.pywith chunks 1 to 3 in the file. It prints the weakest pattern, here graphs, since it was failed.terminalactual output (this chunk adds)practise next: graphs
The whole program
Lines 5–19 are chunk 1, 20–39 are chunk 2, 40–50 are chunk 3. Every chunk starts with a # ── chunk n ── comment. This file lives at code/a3-dsa-reset/mock_tracker.py, with its tests in test_patterns.py.
# A tiny log of your mock rounds that tells you what to practise next. Python 3.12.
from collections import defaultdict
# ── chunk 1: record one mock round ──
LOG = []
def record(pattern, minutes, solved):
LOG.append({"pattern": pattern, "minutes": minutes, "solved": solved})
if __name__ == "__main__":
record("sliding window", 38, True)
record("graphs", 45, False)
record("sliding window", 29, True)
print(len(LOG), "rounds logged")
# ── chunk 2: summarise by pattern ──
def summary(log):
groups = defaultdict(list)
for row in log:
groups[row["pattern"]].append(row)
out = {}
for pattern, rows in groups.items():
out[pattern] = {
"rounds": len(rows),
"solved_pct": round(100 * sum(r["solved"] for r in rows) / len(rows)),
"avg_minutes": round(sum(r["minutes"] for r in rows) / len(rows), 1),
}
return out
if __name__ == "__main__":
for pattern, s in summary(LOG).items():
print(f"{pattern:15} {s['rounds']} rounds, {s['solved_pct']}% solved, {s['avg_minutes']} min average")
# ── chunk 3: pick the pattern to practise next ──
def weakest(log):
"""Lowest solve rate first; ties go to the slower pattern. None if the log is empty."""
s = summary(log)
if not s:
return None
return min(s, key=lambda p: (s[p]["solved_pct"], -s[p]["avg_minutes"]))
if __name__ == "__main__":
print("practise next:", weakest(LOG))
3 rounds logged
sliding window 2 rounds, 100% solved, 33.5 min average
graphs 1 rounds, 0% solved, 45.0 min average
practise next: graphs
Read the output. With three sample rounds, the tracker shows sliding window at 100% and 33.5 minutes average, graphs at 0%, and picks graphs. That is the whole point of the tool: you may feel strongest at graphs because you enjoy them; the log says otherwise.
Mission: run one timed 45-minute mock every week for four weeks, log each in mock_tracker.py, and let the tracker choose what to practise next. At the end you have four logged rounds and a clear weakest pattern.
- Each mock uses
python3 timed_round.py <problem> 45and you speak all seven steps aloud (record yourself on your phone) - Each round's tests live in a file and pass with
pytest, including the empty input and one case from the problem's edge list - Each mock is logged with
record(pattern, minutes, solved); after four weeksweakest()names a pattern, and you have solved two fresh problems in that pattern in under 20 minutes each - Measurement: your average minutes per solved problem falls between mock 1 and mock 4, and you write the numbers in a short README with the three mistakes you made most often
Stretch goal: do one mock in Java or Go (see the language row in the stack table) and write down what was slower to write, and what was faster to run.
12 · Interview radarThe Questions Interviewers Ask While You Code
These are not puzzles. They are the meta-questions asked during the round, and each has a rubric: did you reason with numbers, test your own work, and stay calm.
"What is the time and space complexity of your solution?"
The real test Whether you count the real work, including hidden loops, and say both numbers unprompted.
Strong answer I say the time first, then the space, and name what drives each. For the dict version of Two Sum: "one pass over n numbers, each dict step O(1) on average, so O(n) time; the dict holds up to n entries, so O(n) space." I name hidden costs too, such as a sort at the start, which would make it O(n log n).
Land it Say time and space, name the worst case, and point at the line that dominates.
"Can you do better?"
The real test Whether you can find the repeated work in your own solution.
Strong answer I ask what work is repeated. In the brute force it is scanning for a partner again and again, so I trade memory for a dict. If I am already at the best time, I look at space or constants, and I say plainly "I believe O(n) is a lower bound here because every item must be looked at once." Saying that is a good answer, not a failure.
Land it Name the repeated work, then the tool that removes it, then the new cost.
"How would you test this?"
The real test Whether you think in cases, not just in the happy path.
Strong answer I use five groups: the example from the problem, an empty input, a single item, a case with duplicates or ties, and the case that breaks the pattern's rule (for a sliding window, a repeat that sits outside the window, like "abba"). For anything with a fast and a slow version, I compare both on random inputs.
Land it Empty, one, duplicates, the rule-breaker, and a random check against the brute force.
"What if the input does not fit in memory?"
The real test Whether you can reshape the solution for streams and disks without panicking.
Strong answer First I ask which part is large: the input, or the extra memory I use. If the input is read in one pass, a streaming version works, such as a running total or a heap of size k. If a dict of size n is the problem, I can sort the data on disk and compare neighbours, or split it by a hash of the key into pieces that each fit in memory. The trade is more passes over the data for less memory.
Land it Stream it with O(1) or O(k) memory, or split by hash and process one piece at a time.
"Why did you choose that data structure?"
The real test Whether you chose by cost, not by habit.
Strong answer I say what operation the loop repeats most and which structure makes it cheapest. "The loop asks whether I have seen a value, so a set makes that O(1); a list would make the loop O(n²). I considered sorting and two pointers, which saves memory but changes the order of the output." Naming the rejected option shows judgement.
Land it Name the repeated operation, the structure that makes it cheap, and one alternative you rejected.
"What if the numbers can be negative, or the list is empty?"
The real test Whether you checked assumptions before the interviewer had to point them out.
Strong answer I treat this as part of step one, the clarifying questions, and say what changes. For negatives, a sliding window breaks because adding an item no longer only grows the total, so I switch to prefix sums with a dict. For the empty list, I say what to return and trace the code on it.
Land it Ask about empty, negative and duplicate inputs before coding, and say which pattern each one changes.
"You seem stuck. What are you thinking?"
The real test Whether you can stay calm and narrate a search, not freeze.
Strong answer I say it plainly: "I have the brute force, O(n²). I am looking for the repeated work. I am checking whether a dict or a sort removes it." If I still have nothing after a minute, I say "I will code the brute force and then optimise", and do. That keeps me moving and gives the interviewer something to react to.
Land it Narrate the search, and if stuck, ship the brute force and improve it.
There are no dumb questions
- Should I write tests during the round, or is that wasting time?
- Write a few asserts at the end, or trace by hand. Five minutes of tests at the end is worth more than five more minutes of code. Many interviewers say outright that testing is a graded step.
- Is it acceptable to use Python built-ins like
sorted,Counterandheapq? - Yes, unless the interviewer says otherwise. Using them well shows fluency. Ask once at the start: "Is it fine to use the standard library?" If the problem is "implement a heap", then you must write it.
- What if I know the problem and the exact solution?
- Say so. Interviewers prefer honesty, and they will give you a different problem. Pretending to discover a memorised answer is easy to spot and counts against you.
- How many problems should I solve in total?
- The plan above has about 25 practice problems plus 12 worked ones. Quality beats volume: solving 40 problems with full review teaches more than 150 skimmed. The signal that you are ready is naming the pattern correctly for 25 of the 30 drill problems and finishing mocks inside the time.
- What do I do when I make a mistake mid-round?
- Say so calmly, fix it, and keep going: "that is off by one, the window width needs plus one". Interviewers watch how you recover, not whether you ever slip.
For a hiring manager, a coding round is a cheap sample of how a candidate breaks down an unfamiliar problem, states trade-offs, and checks their own work. These are the same habits that prevent production incidents. A candidate who says "this is O(n²) and will time out at ten thousand rows, so I will index it with a dict" shows, in miniature, the judgement a senior engineer uses on real systems.
The pitch to yourself: you are not memorising puzzles, you are making that judgement fast and visible.
13 · RecapWhat You Can Do Now
- You can measure growth with a stopwatch and say, with real numbers, why an O(n²) answer fails at scale and an O(n) one does not
- You can pick the right Python built-in for a job, and name the hidden loop in
in list,pop(0)and slicing - You can read a one-line problem and name its pattern from the signal words, across twelve patterns
- You can build a solution in chunks: brute force, the better idea, and a random test that compares the two
- You can run a 45-minute round with seven steps and a sentence to say at each
- You can use an AI assistant in a round: state the plan, write your own tests, and catch a plausible wrong draft
- You can answer "what is the complexity?", "can you do better?" and "how would you test this?" in speakable sentences
- You can plan four weeks of practice, log your mocks, and let the tracker choose your weakest pattern
From this page: close it and write the five lines of the sliding-window loop from memory, then say what goes wrong if you remove and last_seen[ch] >= left. Then name the pattern and the structure for: "merge k sorted lists", "fewest steps through a maze", and "smallest value that works".
From Module 08: a retriever scores 100,000 chunks and must return the best 5. Which data structure from this page keeps the best 5 as it scans, and what is the cost per chunk compared with sorting all 100,000?
Reveal the answer to the Module 08 question
A min-heap of size 5: push each chunk's score, pop the smallest when the size passes 5. Each step costs O(log 5), which is a small constant, so the whole scan is about O(n) with a tiny factor, instead of O(n log n) for sorting everything. This is the top-k pattern, and it is how many vector search libraries combine partial results.