← All paths · 全部路径

From loops to graphs and dynamic programming

Anyone who can write a variable, an if and a function in any programming language.

从循环写到图与动态规划;每个程序都要有一个会让它出错的小例子。

A sample plan written with AI help, not a person’s story. Found a mistake? Say so in the room. · 示范计划,AI 协助编写,不是真人经历。发现错误,请到讨论室说。

Weeks 1–13 · 第 1–13 周
  1. 1Write a loop that adds the integers from 1 to n. Do not use a formula.

    Check: n = 100 must give 5050 and n = 0 must give 0. An off-by-one gives 4950.

  2. 2Find the largest value in a list and the index where it first appears.

    Check: Try all negatives, equal largest values and one item. Starting from 0 fails on −5, −2.

  3. 3Print every unordered pair from a list, then count the inner loop steps.

    Check: Ten items give 45 pairs, from n(n − 1)/2. Look for pairs repeated in reverse.

  4. 4Write linear search returning the first index, or −1 when the value is absent.

    Check: Test empty, first, last, missing and repeated. Returning −1 inside the loop too early is common.

  5. 5Implement binary search on a sorted list and count comparisons of the middle item.

    Check: Search every value in 0 to 999. No search may examine more than 10 middle items.

  6. 6Write one sentence that stays true before each binary search round. Print it as an assertion.

    Check: Search absent values below, between and above. A false assertion shows the first bad boundary change.

  7. 7Code insertion sort and count how many items shift.

    Check: Reversed input of five distinct items takes 10 shifts; sorted input takes 0. Test duplicates too.

  8. 8Merge two already sorted lists without calling a sort function.

    Check: Use [], [1, 1, 4] and [2], [1, 3]. Output length must equal both input lengths added.

  9. 9Write recursive power by halving the exponent, with integer exponent at least 0.

    Check: 3¹³ must be 1594323. Test exponent 0, and count calls for exponent 1000.

  10. 10Build merge sort from recursion and the merge function.

    Check: Compare with the built-in sort on 1000 random lists, including duplicates and length 0 or 1.

  11. 11Use a stack to check brackets (), [] and {} in a line.

    Check: ([)] must fail although counts match. Also try a lone closer, a lone opener and an empty line.

  12. 12Implement a fixed-size circular queue with front position and item count.

    Check: Fill it, remove two, add two, then empty it. Order must survive the index returning to 0.

  13. 13Review: code week 5 binary search with the old file closed. Open it afterward and write what changed at each boundary.

    Check: Test 0, 1, 2 and 3 items against linear search, including every absent gap.

Weeks 14–26 · 第 14–26 周
  1. 14Build prefix sums so any range total needs one subtraction.

    Check: In [3, 1, 4, 1, 5], the second to fourth items total 6. Compare all ranges with direct addition.

  2. 15In a sorted list, find two different positions with a chosen sum using two moving indexes.

    Check: For [2, 4], sum 4 must fail. Compare with all pairs on random small lists.

  3. 16Find the longest part of a word with no repeated letter using a moving window.

    Check: "balloon" gives 3. Use "abba" to detect a left edge that moves backward.

  4. 17Count words with a hash map and list them by count, then alphabetically.

    Check: Choose capital and punctuation rules first. Counts must sum to the number of accepted words.

  5. 18Write a small hash table with 8 slots, each holding a list of key-value pairs.

    Check: Insert keys that share a slot, update one and delete another. The remaining values must not change.

  6. 19Implement a singly linked list with add at end, remove value and reverse.

    Check: Remove first, middle, last and missing items. Reverse twice and compare with the original order.

  7. 20Represent a binary tree and write preorder, inorder and postorder visits.

    Check: Draw a three-level tree and trace it by hand. Each visit list must contain every node once.

  8. 21Build a binary search tree with insert and search, deciding a duplicate rule first.

    Check: Inorder must be sorted. Insert 1 to 100 in order and measure height: 100 nodes deep.

  9. 22Implement a minimum heap with insert and remove smallest.

    Check: After each operation, every parent must be at most its children. Remove until empty and expect sorted order.

  10. 23Find the k largest values by keeping a heap of only k items.

    Check: Compare with sorting for k = 0, 1 and full length. Print maximum heap size.

  11. 24Partition a list around one value, then use it to find the k-th smallest.

    Check: Try all equal values and reversed input. Compare every k with a sorted copy.

  12. 25Process half-open intervals by sorted start and end events to find maximum overlap.

    Check: [1, 4), [2, 6), [5, 7) gives 2. For [1, 2), [2, 3), expect 1: ends come first.

  13. 26Review: create tests for week 10 merge sort before coding it again. Time both programs and write what changed.

    Check: Double input size four times. Growth near four times per doubling suggests quadratic work.

Weeks 27–39 · 第 27–39 周
  1. 27Choose the most non-overlapping intervals by earliest finishing time, and write an exchange argument.

    Check: Compare with trying all subsets for up to ten intervals. Choosing shortest first should fail somewhere.

  2. 28Write greedy coin change for coins 1, 3 and 4, then search by trying all combinations.

    Check: For 6 greedy uses 3 coins and the best uses 2. Keep this failing test.

  3. 29Generate all subsets by recursion with choose, continue and undo.

    Check: Five distinct items give 32 subsets with no repeats. Print state after return to detect a missed undo.

  4. 30Count placements of n queens on an n by n board, none attacking another.

    Check: n = 4, 5, 6 must give 2, 10, 4. A missing diagonal check gives too many.

  5. 31Count search calls in the queen program with and without early rejection.

    Check: Both versions must return identical placement counts. Fewer calls alone does not prove rejection is safe.

  6. 32Store an undirected graph as neighbor lists and write functions to add an edge and print degrees.

    Check: Degrees must sum to twice the edges. Decide how repeated edges and self-edges are handled.

  7. 33Use breadth-first search to find fewest edges from one node to all others.

    Check: Add a cycle and an unreachable node. Compare distances with hand levels; mark visited when queued.

  8. 34Find connected components with depth-first search, recursively and with your own stack.

    Check: Use isolated nodes and a 10000-node path. Component sets must match even if visit order differs.

  9. 35Topologically sort a directed graph by repeatedly removing a node with no incoming edge.

    Check: For every edge, its start must come first. A cycle must return fewer nodes and be reported.

  10. 36Implement Dijkstra with a priority queue for non-negative edge weights.

    Check: Compare with trying all simple paths on tiny random graphs. Skip queue entries whose distance is outdated.

  11. 37Run finalized-node Dijkstra on S→A 2, S→B 5, B→A −4 and explain its mistake.

    Check: It fixes A at 2, while S→B→A costs 1. Identify the assumption about later edges.

  12. 38Implement union-find with path compression and union by size.

    Check: Compare connectivity with breadth-first search after each of 200 random merges. Repeated merges must not change sizes.

  13. 39Review: repeat week 33 breadth-first search, now recovering one route. Note what changed in the stored data and why.

    Check: Every route step must be an edge, and length must equal distance. Test start equals target.

Weeks 40–52 · 第 40–52 周
  1. 40Use Kruskal's method and union-find to build a minimum spanning tree.

    Check: A triangle with weights 1, 2, 3 gives total 3. A disconnected graph must be reported.

  2. 41Implement Bellman-Ford with parents and a check for reachable negative cycles.

    Check: Revisit S→B→A with total 1. Add an unreachable negative cycle; it should not affect S.

  3. 42Write Fibonacci by plain recursion and with stored results. Count function calls.

    Check: With base cases 0 and 1, plain recursion for 20 uses 21891 calls. Both return 6765.

  4. 43Count right-and-down paths in a grid with blocked cells using a table.

    Check: A 3 by 3 cell grid gives 6; blocking the center gives 2. Test a blocked start.

  5. 44Compute fewest coins, then count unordered ways, for coins 1, 3, 4 and total 6.

    Check: The answers are 2 and 4. A way count above 4 probably counts reordered coins twice.

  6. 45Implement 0/1 knapsack in a table, then compress it to one row.

    Check: Weights 1, 3, 4, values 1, 4, 5, capacity 7 give 9. Wrong loop direction reuses items.

  7. 46Find the longest common subsequence length of two words and recover one answer.

    Check: "planet" and "plate" give 4. Check recovered letters appear in order in both words.

  8. 47Compute edit distance with insert, delete and replace, then recover the operations.

    Check: "stone" to "tones" costs 2, not 5. Apply recovered operations and compare the final word.

  9. 48Find longest strictly increasing subsequence length in quadratic time, then by binary search.

    Check: [3, 1, 4, 1, 5, 9, 2, 6] gives 4. Random duplicates detect non-strict comparisons.

  10. 49On a tree, choose the most nodes with no chosen neighbors using take and skip values.

    Check: A five-node path gives 3 and a star with four leaves gives 4. Compare all subsets.

  11. 50Find the longest weighted path in a directed graph without cycles, using topological order.

    Check: Include negative weights and unreachable nodes. Starting every distance at 0 will invent routes.

  12. 51Build a tester that generates small cases, compares two solutions and shrinks the first failure.

    Check: Plant three bugs in old programs. A surviving bug shows which case your generator never creates.

  13. 52Review: shuffle weeks 28, 36 and 45. Name each method, code it again, and write what changed in your choices.

    Check: Run the week 51 tester on all three. Record wrong method, wrong state or coding slip separately.