C3. Coding patterns page (lesson 6)
The page you write
Lesson 6 gives every pattern a cue, a template, a fallback, a trap, a follow-up sentence and, last, what changes when the input is too big, streaming or online. The table keeps the cue and the last item; the sentences are the author's construct, not an interviewer's list. Copy the rows for the patterns you are weakest at.
Table: Pattern, Cue in the statement, If it is too big, streaming or online (18 rows)
| Pattern | Cue in the statement | If it is too big, streaming or online |
|---|---|---|
| 1. Two pointers | Sorted input; a pair or triple with a target | Stream: a hash set of seen values. On disk: external sort, then two readers. |
| 2. Sliding window | Longest or shortest contiguous run under a rule | Keep only the window and its counts; memory is the window. |
| 3. Prefix sums | Count subarrays with sum k; many range queries | The map grows without bound: drop old prefixes if only a recent window matters. With updates, use a Fenwick tree. |
| 4. Intervals | Merge, insert, overlap | Online: a TreeMap by start. Too big: external sort by start, then one pass. |
| 5. Monotonic stack | Next greater or smaller, nearest on one side | Already online; memory is the waiting indices. |
| 6. BFS and DFS | Reach, steps, level order on a grid, graph or tree | Generate neighbours on the fly and bound the frontier; a Bloom filter can stand in for the seen-set. |
| 7. Topological sort | Prerequisites; order with dependencies | Edges arrive: keep in-degrees. Online cycle detection is harder; say so. |
| 8. Union-find | Groups that merge as edges arrive | Already online, O(n). Sparse ids: key a HashMap by id. |
| 9. Binary search on the answer | "Smallest X that works"; the test is monotone | Range to 10^18 is fine with long. On a stream there is nothing to test: store it or take a second pass. |
| 10. Heaps, two heaps | Top k, k-th, merge k lists; running median | A size-k heap holds a stream in O(k). Median: two heaps. Many machines: a heap per shard, then merge. |
| 11. Backtracking | All permutations, combinations, subsets | Too many to list: ask for a count (DP or a formula) or yield one at a time. |
| 12. Dynamic programming | Ways, minimum cost, reachable, longest subsequence (C4) | Roll to one or two rows. Rebuilding the answer needs the full table, or Hirschberg (named, not coded). |
| 13. Trie | Prefix queries, autocomplete | Millions of words: a radix tree, or the dictionary on disk. Inserts stream in, O(L) each. |
| 14. Bit tricks | The one value that appears once; masks | The XOR fold reads once in O(1) memory. Across machines: XOR each part, then XOR the results. |
| 15. Shortest paths | Weighted: Dijkstra. Weights 0 or 1: 0-1 BFS (a deque). At most k stops: k rounds over a copy | Build the map on the fly; stop when the target leaves the heap. A* or two-ended search (named). Costs change: rerun. |
| 16. Sweep line | Meeting rooms, most overlap, events in time | Online: a TreeMap of +1 and -1 (O(n) a booking). Too big: external sort, then a heap of ends. |
| 17. Fenwick, segment tree | Range sum or min with point updates | Already online. A huge index range: compress coordinates, or a dynamic segment tree (named). |
| 18. Quickselect | k-th smallest of an array in memory | Needs the whole array. Stream: a size-k heap. Bounded values: one counting pass. Machines: counts by value range. |
Neighbours that get confused
- Heap or quickselect: a heap if the data streams or k is small; quickselect if the array is in memory and you ask once.
- BFS, 0-1 BFS or Dijkstra: equal weights, weights 0 or 1, other non-negative weights. Negative weights need another method.
- Prefix sums or Fenwick tree: the array never changes, or it changes between queries.
Next stop: C4. Coding: the DP families (lesson 6), 2 min
C4. Coding: the DP families (lesson 6)
The page you write
Code, 5 lines
Name the state in one sentence BEFORE any code. Plain recursion first -> memo (int[][] filled with -1) -> table if time. Recursion depth near n risks StackOverflowError: go bottom-up. Order of fill: every dp cell I read must already be final. Answer where? ____ Do they want the number or the items? ____
Six families from lesson 6 and its web appendix, each with the line to say aloud. The state and recurrence are the standard ones, restated by the author for the sheet.
Table: Family, State, Recurrence, Cost and trap (6 rows)
| Family | State | Recurrence | Cost and trap |
|---|---|---|---|
| Fewest coins (one-dimensional) | dp[a] is the fewest coins for amount a | dp[a] = min over coins of dp[a - c] + 1 | O(amount x coins) time, O(amount) space; use amount + 1 as infinity |
| Longest common subsequence (two-dimensional) | dp[i][j] is the answer for the first i and first j letters | match: diagonal + 1; else max(above, left) | Two rows give the length; the string itself needs the full table |
| Longest increasing subsequence | tails[k] is the smallest tail of a run of length k + 1 | binary-search the first tail >= x and overwrite it | O(n log n); keep indices to rebuild the run |
| 0/1 knapsack | dp[c] is the best value at capacity c | dp[c] = max(dp[c], dp[c - w] + v), c downward | Downward means each item once; naming the items needs the full table |
| Edit distance | dp[i][j] is the edits for the first i and first j letters | equal: diagonal; else 1 + min of the three neighbours | O(m x n); the edit script is read back from the table |
| Stock with cooldown | hold, sold and rest on each day | hold = max(hold, rest - p); sold = hold + p; rest = max(rest, sold) | O(n); the trades need the arrays walked back |
Five moves
- Say the choice made at each position and why the sub-answers overlap.
- Write the state in one sentence, then the recurrence in one line.
- Pick the order of fill, and the base row or column.
- Trace the smallest example by hand.
- Take the follow-up: "now give me the items, not the number" (keep the table, walk back) and "the table is too big" (roll the rows).
Python: @functools.cache on the recursive function gives the memo in one line.
Next stop: C5. Coding: Java 21 idioms (lesson 6), 1 min
C5. Coding: Java 21 idioms (lesson 6)
The page you write
The idioms the lesson 6 listings use, to type without looking. The block is a program that was compiled and run with java --source 21 Idioms.java (OpenJDK 25, 1 November 2026); the helper ok, which throws AssertionError when its test is false, is left out of the print.
Code, 56 lines
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.TreeMap;
public class Idioms {
// ok(cond, msg): throws AssertionError when cond is false
public static void main(String[] args) {
// min-heap of {dist, node} by dist; compare, never subtract
PriorityQueue<long[]> pq =
new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0]));
pq.add(new long[] {9, 1});
pq.add(new long[] {3, 2});
ok(pq.poll()[0] == 3, "min-heap");
// max-heap of ints; k-largest keeps a MIN-heap of size k
PriorityQueue<Integer> maxHeap =
new PriorityQueue<>(Collections.reverseOrder());
maxHeap.add(4);
maxHeap.add(7);
ok(maxHeap.peek() == 7, "max-heap");
// sort intervals by start without overflow
int[][] iv = {{5, 8}, {1, 3}};
Arrays.sort(iv, (a, b) -> Integer.compare(a[0], b[0]));
ok(iv[0][0] == 1, "sort by start");
// deque as stack (push/pop) and as 0-1 BFS queue (addFirst/addLast)
Deque<Integer> st = new ArrayDeque<>();
st.push(1);
st.push(2);
ok(st.pop() == 2, "stack");
// count with merge; default with getOrDefault
Map<String, Integer> cnt = new HashMap<>();
cnt.merge("a", 1, Integer::sum);
cnt.merge("a", 1, Integer::sum);
ok(cnt.get("a") == 2 && cnt.getOrDefault("z", 0) == 0, "merge");
// sorted map: floor/ceiling are O(log n) "nearest" queries
TreeMap<Integer, String> tm = new TreeMap<>();
tm.put(10, "x");
tm.put(20, "y");
ok(tm.floorKey(15) == 10 && tm.ceilingKey(15) == 20, "floor");
// midpoint that cannot overflow; long for sums and products
int lo = 2_000_000_000, hi = 2_100_000_000;
ok(lo + (hi - lo) / 2 == 2_050_000_000, "mid");
ok(1_000_000 * 1_000_000L == 1_000_000_000_000L, "long");
}
}
Python: heapq.heappush(h, (d, v)) is the min-heap push; collections.deque and bisect cover the deque and sorted-map lookups.
Next stop: C6. Machine coding (lesson 7), 2 min
C6. Machine coding (lesson 7)
The page you write
Code, 10 lines
Clock: 0-10 clarify + scope | 10-20 skeleton | 20-55 must-haves
55-70 error paths | 70-82 bonus + extension | 82-90 clean + notes
Patterns: strategy, state, observer, factory, builder, command,
repository, decorator. Reach for one only if a requirement needs it.
State machine (order, vending, elevator): a table (state, event) -> state;
look up and refuse BEFORE the history entry and the change. Test every
pair: 6 legal and 24 illegal in the lesson's order, each illegal one
leaves state and history unchanged. Threads: sheet C7.
Out of scope (say it aloud): ______________________________
Extension I expect: ________________ Run command: ________________Five moves
- Spend ten minutes on questions and a written scope; list what you will not build.
- Lay out the skeleton in ten minutes: classes, interfaces, one happy path that runs.
- Build must-haves in the next 35 minutes, one runnable step at a time.
- Add error paths for 15 minutes; on each failure check that nothing changed, and run the tests.
- Use the last 20 minutes for one extension, clean up and write notes on what you left out, including that the design is single-threaded if it is.
Paper drill
Run a 90-minute timer on one design from lesson 7, such as the parking lot (lesson 7 gives it 11 test scenarios), and write what is runnable at each boundary.
Table: Rubric line, Done (8 rows)
| Rubric line | Done |
|---|---|
| Core flow runs: the driver calls every must-have | |
| Scope fits the time: extras cut, not half-built | |
| Classes have one job; a pattern only where a requirement needs it | |
| Nothing changes before every check has passed | |
| A lifecycle is a transition table, tested on every pair | |
| Errors named and tests cover at least one error path | |
| Extension landed as one class and one line of wiring | |
| Notes say what is out and where the design stops |
Next stop: C7. Concurrency one-pager (lesson 7), 2 min
C7. Concurrency one-pager (lesson 7)
The page you write
Code, 11 lines
Say it first: "single-threaded; the ceiling is ___ ; next I would ___". Three race shapes (the author's grouping, not a standard): 1 check-then-act two gates both see one free spot and both take it 2 read-modify-write count++ is read, add, write; two threads lose one 3 two fields move together a transfer debits one, credits the other Fix: make check and act ONE step, or hold ONE lock around both. Locks vs atomics: one variable -> atomic (AtomicInteger, LongAdder); a check plus a change on more than one variable -> lock; per key in a map -> ConcurrentHashMap.compute(key, ...) Two locks -> take them in one fixed order (deadlock). Visibility: a flag read by another thread needs volatile or a lock.
The block holds a fix for each shape. It was compiled and run with java --source 21 Races.java (OpenJDK 25, 1 November 2026): 100 threads fought for 10 spots and exactly 10 won, 8 threads added 80,000 and none was lost, and two threads moving money in opposite directions kept the total and did not deadlock. The test harness is left out of the print; a thread test can pass by luck, so it shows a fix works, not that a race is gone.
Code, 41 lines
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;
class Races {
// Shape 1, check-then-act: the check and the change must be one step.
static class Spots {
private final AtomicInteger free;
Spots(int n) { free = new AtomicInteger(n); }
boolean take() { // one variable: compare-and-set
int f;
do {
f = free.get();
if (f == 0) return false; // check
} while (!free.compareAndSet(f, f - 1)); // act, only if unchanged
return true;
}
}
// Shape 2, read-modify-write: count++ is a read, an add and a write.
static final LongAdder entered = new LongAdder();
// Shape 3, two fields change together: one lock must cover both.
static class Account {
final int id;
long cents;
Account(int id, long cents) { this.id = id; this.cents = cents; }
}
static boolean transfer(Account a, Account b, long amt) {
Account first = a.id < b.id ? a : b, second = first == a ? b : a;
synchronized (first) { // fixed order: no deadlock
synchronized (second) {
if (a.cents < amt) return false; // check + change, both locks
a.cents -= amt;
b.cents += amt;
return true;
}
}
}
}Five moves
- Name the shared state: which fields can two requests touch at once?
- Find the check-then-act, the read-modify-write and the multi-field change.
- Pick the smallest tool: an atomic for one variable, a lock for a rule over several.
- Test with many threads and an invariant (spots sold, total money), then say the test cannot prove it.
- Say what you left out: fairness, timeouts, a distributed version.
Next stop: C9. System design add-ons (lesson 8), 2 min
C9. System design add-ons (lesson 8)
The page you write
Five topics that lesson 8 treats after the building blocks. Every number is an assumption made in the lesson for its own invented example, not a measurement.
Table: Topic, The line to say, Numbers to have ready (5 rows)
| Topic | The line to say | Numbers to have ready |
|---|---|---|
| Chat | One writer per conversation hands out the next sequence number, never the client clock; a retry carries the same client_msg_id and gets the same number. Delivered and read are cursors, not flags on messages. Presence is written on connect and disconnect, not on every heartbeat. | Assumed: 500 million users, 100 million sockets at peak, 1,000 gateways of 100,000 sockets, about 1.8 million deliveries a second. The load is the connection tier, not the store. |
| Geo-matching | A geohash cell for the driver table; read the rider's cell and its eight neighbours, never the cell alone. Keep the latest positions in memory. A driver is held for one offer at a time. | Length 6 is about 1.22 km by 0.61 km at the equator; 1 million drivers every 4 s is 250,000 updates a second, 100 MB of latest positions. |
| Database | Choose by the query, then the product. Relational: rows change together. Key-value: exact key. Wide-column: a log per entity, huge writes. Document: whole records. Search: text relevance, never the only copy. Say the cost with the choice. | Secondary index = a second write. Log-structured trees favour writes; B-trees favour reads and ranges (author's reading). |
| RTO and RPO | RPO is the data you may lose, measured in time; RTO is the time until service returns. Asynchronous replica: data at risk = lag x write rate. The drill: detect from outside, decide, fence the old primary, promote, repoint, check, announce. | At 2,400 writes a second: 1 s of lag risks 2,400, 5 s risks 12,000. A synchronous second site at 60 ms holds about 144 commits in flight. |
| SLO | SLI = good events / valid events; SLO = the target over a window; error budget = 100% minus the SLO. Alert fast burn to page, slow burn to ticket. | 99.9% over 30 days = 43.2 minutes; 99.99% = 4.32. Burn rate 14.4 spends 2% of the budget in an hour (14.4 / 720). |
Five moves
- Chat: state the ordering rule and the receipts before any box.
- Matching: size the update rate first; the match rate is small.
- Database: name the query, the family, and the cost you accept.
- Region loss: give RPO and RTO as numbers, and who is fenced.
- Operating: give the SLO, the budget in minutes, and two alerts.
Next stop: C11. Hiring manager (lesson 10), 1 min
C11. Hiring manager (lesson 10)
The page you write
Code, 6 lines
Page fields: Relevance | Scope | Decisions | Motivation | Concerns
Questions: seat, level, gap, level risk, bar, decision path;
scope, on-call, promotion, manager style, overlap
Heard from them (use two by name): ____________ / ____________
Two decisions with costs: ______________ / ______________
The doubt I will close on: ______________________Five moves
- Listen first: ask what the team needs before you pitch.
- Pitch in about a minute: system and users, the proof closest to their problem, one more result, why this team.
- Give two decisions, each with the cost you accepted.
- Say what was yours and what was not; ask questions that need a number or an example to answer.
- Close on the doubt you can hear and answer it.
Paper drill
Run the thirty-minute manager call from lesson 10 out loud with a friend as manager: small talk 3, their team 5, your pitch 4, a project 8, your questions 8, close 2. Ask them to interrupt twice. If you may be down-levelled, rehearse the concrete questions lesson 10 gives for that moment.
Table: Rubric line, Done (6 rows)
| Rubric line | Done |
|---|---|
| I listened first | |
| I pitched in order | |
| I gave two decisions with costs | |
| Credit was precise | |
| My questions forced facts | |
| I closed on the doubt |
Next stop: C12. Offer (lesson 12), 1 min
C12. Offer (lesson 12)
The page you write
Code, 8 lines
Offer: fixed ___ variable ___ bonus ___ stock ___ level ___ Year-1 cash: ___ Year-2 cash: ___ (no one-time items) My ask: +___ gross nets ___ (template T3) Net a month: ___ Example only, invented base of 23,06,500 taxable, new regime (lesson 12): +1 lakh nets 73,662; +2 lakh nets 1,42,462; +4 lakh nets 2,80,062 (first 93,500 at 25%, rest at 30%, 4% cess). Yours will differ. My number: ___ My reason: ____________ Deadline: ____ Written offer first. Never say a number I would not accept.
Five moves
- Ask for the offer in writing with the level and the annexure before you discuss a number.
- Compare year-1 and year-2 cash; count stock you cannot sell at an amount you would accept losing.
- Say the net of every ask to yourself before you say the gross aloud.
- Ask for one package, with a reason, and stay silent after the number.
- Take time in writing. On a counter-offer, write the reason you left first (the author's reading: it changes the number, not the reason).
Paper drill
Rehearse six scripts with a friend as recruiter: one package; a joining bonus covering a buyout; a level below interview; a competing offer; deadline pressure; a counter-offer.
Table: Rubric line, Done (6 rows)
| Rubric line | Done |
|---|---|
| Offer in writing | |
| Year-1 and year-2 cash computed | |
| Net of each ask known | |
| One package asked, with reason | |
| No figure given that I would refuse | |
| Clawback and buyout terms noted |
Next stop: C13. AI-assisted round (AI lesson), 1 min
C13. AI-assisted round (AI lesson)
The page you write
Code, 6 lines
Allowed? ___ (ask in writing; if not stated, assume not) One third-party account of one format (AI lesson, Figure A.3, reported by candidates, not a company rule): 60 min = fix a bug, build, optimise Each prompt: constraint + the code. After each accepted change: run tests. Reject or rewrite one suggestion, say why. Add one edge-case test. I can explain every line I keep.
Five moves
- Read the failing test and the files before the first prompt.
- Write prompts that name a constraint and include the code.
- Run the tests after every accepted change.
- Reject or rewrite one suggestion and say why aloud.
- Add an edge-case test and explain every line you keep.
Paper drill
Set a 60-minute timer with a small repository and a failing test. Use a tool only as the round allows. A friend watches for the six items below.
Table: Rubric line, Done (6 rows)
| Rubric line | Done |
|---|---|
| Read before prompting | |
| Prompts named a constraint | |
| Tests after each change | |
| Rejected one suggestion | |
| Edge-case test added | |
| Explained every kept line |
Sources
3 sources
- Lessons 4 to 12 and the AI lesson of this guide, each of which lists the primary sources for its own times and counts.
- Income-tax Act, 2025, as summarised in lesson 0, read 31 Oct 2026; the net figures on sheet C12 follow lesson 12.
- Sheet C5 and sheet C7 listings: compiled and run with
java --source 21on OpenJDK 25, 1 Nov 2026; the race groupings on C7 are the author's construct.