Use this preserved workbook with the original on-site expanded reader. Older publisher and textbook readings are optional references. Work independently, then compare each explained solution. Practice and projects are voluntary. Cases and datasets are fictional unless a primary passage is explicitly named.
An invariant is an argument about every iteration
A correctness argument has initialization, preservation and termination obligations. An invariant true initially but broken by an update proves nothing about the final result. Conversely, a useful invariant need not mention every implementation variable: it must be strong enough to connect the termination condition to the postcondition. Time complexity is a separate argument about the number and cost of operations.
For a first-match search, the processed prefix contains no match. Returning the first encountered equality is justified because every earlier candidate has already been ruled out. An all-match search needs a different invariant: the output contains exactly the matching indices in the processed prefix. Confusing the specifications leads to incorrect early termination.
Worked problem
Specify and justify a scan that returns all indices of 7 in [7,2,7,7]. State an invariant before processing index i.
Trace the complete solution
Before i=0 the result is empty, exactly matching the empty prefix.
At iteration i, append i if and only if items[i] equals 7. This extends the exact-match description from the prefix ending before i to the prefix ending at i.
At termination i=4, the output [0,2,3] covers the entire list. No early return is allowed after the first match.
The scan takes linear comparisons. Output storage can also be linear if every element matches; that is required output, not an accidental leak.
Independent transfer problem
Change the postcondition to return only the last matching index or None. Give an update rule, invariant and result on an empty list.
Compare the reasoning and result
Keep last=None initially. After processing a prefix, last is the greatest matching index in that prefix, or None if none exists. Update last on every match and return it only after the scan. Empty input returns None. The algorithm uses constant auxiliary state and linear comparisons; no list of all matches is needed.
An index trades construction and maintenance costs for faster lookup. Comparing only one lookup ignores the work needed to build the index. For n records and q queries, repeated scans cost on the order of qn comparisons. A hash-based index has expected construction O(n) and expected lookup O(1) per query under ordinary hashing assumptions, but it consumes memory and must remain synchronized with updates. These are expected bounds, not guarantees that collisions never occur.
Choose an index value that preserves the information required by the query. Mapping customer to a single order overwrites history. Mapping to a list preserves multiplicity but makes deletion and ordering policies explicit responsibilities.
Worked problem
A report has 10,000 orders and 1,000 customer queries. Compare repeated complete scans with one customer-to-order-list index, ignoring constants.
Trace the complete solution
Repeated scans examine up to 10,000,000 order positions. An index build visits 10,000 records before the 1,000 expected constant-time key lookups.
Returning matching records still costs at least the number of records returned. O(1) key access does not make a large answer free.
After deleting an order, update both authoritative records and the customer list, or rebuild the index. A stale index can be fast and incorrect.
For a single query on a stream, building the complete index may have no worthwhile advantage. Include memory and update rates in the choice.
Independent transfer problem
Most queries return all 10,000 orders for one customer. Can the indexed report have constant total query time? Explain the lower bound.
Compare the reasoning and result
No. Producing 10,000 results requires at least proportional output work under the ordinary explicit-output model. The index can locate the list quickly, but cannot eliminate the cost of visiting or serializing its contents. Report key-access time separately from result-production time and avoid claiming O(1) for the whole report.
Binary search is easier to reason about when the candidate interval is consistently half-open: [lo,hi). For lower_bound, maintain that every earlier position is below the target and every position at or beyond hi is at least the target. An equality moves hi left because an earlier equal value may exist. The interval shrinks until lo equals hi.
Returning an insertion position and proving a member exists are different tasks. A lower bound equal to len(items) is legal as a boundary and illegal as a direct element access. A membership wrapper must check both the boundary and equality. The precondition that the list is sorted under the same comparison rule is essential.
Worked problem
Trace lower_bound for target 5 in [1,5,5,9], starting lo=0, hi=4 and mid=(lo+hi)//2.
Trace the complete solution
mid=2 holds 5, so hi=2. Equality does not justify returning immediately when the first match is required.
mid=1 also holds 5, so hi=1. Then mid=0 holds 1, so lo=1. The interval is empty at [1,1).
Return 1. Positions before 1 are below 5; the value at 1 is at least 5 and equals it, establishing membership.
For target 10, return 4 and do not access items[4]. The wrapper reports absence after the bounds check.
Independent transfer problem
Give the lower bound and upper bound for 5 in the same list. Explain how to count duplicates without scanning them.
Compare the reasoning and result
The lower bound is 1; the upper bound, first position greater than 5, is 3. Their difference is 2. Upper-bound search moves lo right when value is less than or equal to the target. Two logarithmic boundary searches count the equal range without traversing its elements; returning the actual elements would add output cost.
A recurrence defines both its base cases and the relation among subproblems. For stair counts, ways(0)=1 represents the empty sequence; negative remaining distance contributes zero. This is a counting convention tied to the problem, not a universal rule that every recursive function returns one at zero.
Memoization removes repeated subproblem evaluation but not every resource cost. A recursive memoized function can retain a deep call stack. Bottom-up iteration can keep only the preceding two values for this recurrence. As values grow, arithmetic cost and integer storage can matter even when the number of recurrence steps is linear.
Worked problem
Count ordered sequences of one- and two-step moves covering five stairs. Compare naive recursion with a bottom-up state pair.
Trace the complete solution
Starting with ways(0)=1 and ways(1)=1 gives ways(2)=2, ways(3)=3, ways(4)=5 and ways(5)=8.
Naive recursion recomputes smaller states through multiple branches. Memoization evaluates each remaining-distance state once, while retaining cached results.
An iterative pair holds the preceding two counts and updates them through five. Its invariant identifies those counts at the start of each iteration.
The result counts orders separately: 1+2 and 2+1 are different sequences. An unordered partition problem would require a different recurrence.
Independent transfer problem
Moves may now be one or three stairs. State the recurrence and compute the count for five. Identify the required base convention.
Compare the reasoning and result
Use f(n)=f(n−1)+f(n−3), f(0)=1 and f(n)=0 for n<0. The sequence for n=0 through 5 is 1,1,1,2,3,4. The four sequences for five are all ones and the three placements of one 3 among two 1s. Reusing the one-or-two recurrence would solve the wrong specification even if the memoization were perfect.
Breadth-first search discovers vertices in nondecreasing number of edges from the start when all edges have equal cost. A visited set prevents a cycle from causing repeated exploration. Mark on enqueue so several parents do not schedule the same vertex repeatedly. A parent mapping can reconstruct a discovered path, while a distance mapping records its edge count.
A reachable set does not contain enough information to reconstruct every path. A BFS shortest-path guarantee concerns edge count, not arbitrary travel cost. Introducing weights changes the optimization problem and may require a different algorithm and assumptions about edge signs.
Worked problem
Graph edges are A→B, A→C, B→D, C→D and D→A. Trace BFS from A, enqueueing B before C, and reconstruct one shortest path to D.
Trace the complete solution
Begin queue [A], seen {A}, distance[A]=0. Expanding A enqueues B and C with distance 1 and parent A.
Expand B to discover D at distance 2 with parent B. Expanding C sees D already discovered and does not enqueue it again.
D’s edge back to A does not repeat A. Following parents gives D←B←A, hence path A,B,D.
A,C,D is another path with the same edge count. The chosen tie order does not make it uniquely optimal.
Independent transfer problem
Assign weights A→B=100, B→D=1, A→C=2, C→D=2. Does the earlier BFS parent path minimize cost?
Compare the reasoning and result
No. A,B,D costs 101 while A,C,D costs 4, although both use two edges. BFS remains correct for minimum edge count but does not solve this weighted-cost objective. A suitable nonnegative-weight shortest-path algorithm can compare cumulative costs; the objective and weight assumptions must be documented.
A resource budget includes input storage, auxiliary state, output and transient copies. An iterator-based aggregate may hold little auxiliary state, yet its caller may already have materialized the entire input. A benchmark must identify which costs are included. Reusing an exhausted iterator can make a second algorithm appear artificially fast because it processes no records.
Measure correctness before performance. Use the same logical records, reset the input for every run, count operations where possible and report distributions rather than one favorable time. For memory, distinguish a constant running total from per-customer state that grows with the number of distinct customers.
Worked problem
A generator produces one million transactions. Method A sums it, then Method B indexes the same generator and reports a tiny runtime and zero customers. Evaluate the comparison.
Trace the complete solution
A consumes the iterator. B receives no remaining records, so its output fails the shared logical-input requirement.
Recreate the generator from the same deterministic source for each method. Verify count and total before comparing runtime.
An overall total uses constant aggregate state; an index needs storage proportional to represented keys and records, depending on its output contract.
Include construction costs, query volume and update workload. One timing cannot establish an asymptotic law or a universal winner.
Independent transfer problem
The application only needs the five largest customer totals. Can it always use constant memory while reading unsorted transactions? Explain what must be retained or moved elsewhere.
Compare the reasoning and result
Exact arbitrary customer totals generally require state for customers that may reappear later. Keeping only the current five can discard a customer whose later transactions make it the largest. Aggregate by customer in a mapping, external sort, or database, then select five totals. A fixed-size top-five heap helps after complete customer totals exist; it does not eliminate the grouping requirement.
Implement a fictional work-order query service with linear scan, customer index, ordered boundary search and dependency-graph traversal. Define exactly which query each algorithm answers. Use the same reproducible dataset and include updates, duplicates, missing targets and cycles. Compare correctness, construction cost, per-query cost, output size and memory.
Evidence and evaluation criteria
A precise precondition and postcondition for each distinct query.
Initialization, preservation and termination arguments for scan and boundary search.
Independently calculated results on duplicates, empty inputs and absent targets.
Explicit index consistency behavior after insertion, deletion and conflicting identity.
A cyclic graph trace with parents and a clear distinction between edge-count and weighted paths.
A benchmark that recreates input, verifies answers and includes preprocessing and memory.
Worked project approach and limitations
On [1,5,5,9], verify lower_bound(5)=1, upper_bound(5)=3, and absence for target 10 at boundary 4. Keep event identity separate from equal field values. Build a customer-to-order-list index and demonstrate that a deleted order disappears from both source and indexed queries. For the A,B,C,D graph, show the parent path and explain why changing weights invalidates a cost claim without invalidating reachability. Benchmark fresh generators or equivalent copies so one run cannot exhaust the next. State that a successful finite test suite supports, but does not replace, the correctness argument.
Cumulative assessment
These are new situations. Explain your choice before opening the feedback.
Problem 1
A scan returns after the first match although the contract requires every match. What failed?
The postcondition
Only the runtime measurement
The definition of equality necessarily
Answer and reasoning for every option
Best answer: A
Correct. Early return omits later matches.
Incorrect. The output is already wrong before timing matters.
Incorrect. The equality rule can be correct while stopping is wrong.
Problem 2
A lower bound for 12 in [2,4,8] is 3. What should a membership wrapper do?
Read items[3] to verify the value
Return index 2 because it is nearest
Report absence without indexing position 3
Answer and reasoning for every option
Best answer: C
Incorrect. That index lies outside the list.
Incorrect. Nearest and equal membership are different specifications.
Correct. The boundary equals the list length.
Problem 3
An index finds a list of 50,000 matches in expected constant key-access time. What is the explicit-output cost?
Zero because a hash was used
At least proportional to the 50,000 returned items
Constant for the whole response
Answer and reasoning for every option
Best answer: B
Incorrect. Hash lookup does not produce a free serialized result.
Correct. Serializing the answer takes output work.
Incorrect. Key access does not erase output size.
Problem 4
An iterative recurrence uses constant many integer variables. What qualification matters for very large counts?
The integers themselves can grow in bit length
Each integer always occupies one bit
Iteration guarantees no arithmetic cost
Answer and reasoning for every option
Best answer: A
Correct. A constant number of variables is not necessarily constant bits.
Incorrect. Representation size grows with magnitude.
Incorrect. Updates still perform arithmetic.
Problem 5
A graph has a one-edge path costing 50 and a two-edge path costing 4. What does ordinary BFS optimize?
Total weighted cost
Every possible notion of shortest
Number of edges
Answer and reasoning for every option
Best answer: C
Incorrect. Equal layer distance can conceal different costs.
Incorrect. The optimization objective must be specified.
Correct. Its layer ordering does not compare arbitrary weights.
Problem 6
A customer index is not updated after an order deletion. What describes the result?
A harmless display issue in every case
A consistency failure despite fast lookup
Proof hashing is asymptotically slow
Answer and reasoning for every option
Best answer: B
Incorrect. The query can return an order that no longer exists.
Correct. The index no longer represents the authoritative records.
Incorrect. Staleness does not determine asymptotic complexity.
Problem 7
For one-or-three stair moves, how many ordered sequences cover four stairs?
3
5
2
Answer and reasoning for every option
Best answer: A
Correct. The sequences are 1+1+1+1, 1+3 and 3+1.
Incorrect. That imports the one-or-two recurrence.
Incorrect. That collapses the two distinct orders involving 3.
Problem 8
A binary search uses one ordering to sort and another to compare. What is at risk?
Only the spelling of variables
Nothing if the loop terminates
Its sorted-input precondition
Answer and reasoning for every option
Best answer: C
Incorrect. The mismatch changes the correctness argument.
Incorrect. Termination does not establish correct membership.
Correct. The maintained interval claims rely on a consistent ordering.
Problem 9
A hash index is built for one query over a file. Which comparison is fair?
Assume indexing always loses
Include index construction and memory
Time only the final dictionary lookup
Answer and reasoning for every option
Best answer: B
Incorrect. Repeated workloads or reuse can change the tradeoff.
Correct. The query does not receive a free preexisting index unless the workload provides one.
Incorrect. That hides work required to answer this query.
Problem 10
Why mark a BFS vertex seen when it is enqueued?
To prevent multiple frontier entries for the same discovery
To prove all graph edges have positive weights
To reconstruct all possible paths automatically
Answer and reasoning for every option
Best answer: A
Correct. Several parents may otherwise schedule the same vertex.
Incorrect. Visited state does not constrain weights.
Incorrect. A seen set alone does not store every path.
Problem 11
A second benchmark consumes an exhausted iterator. What is required?
Declare the second algorithm faster
Multiply its time by the input size
Recreate equivalent input and validate outputs
Answer and reasoning for every option
Best answer: C
Incorrect. It performed a different, empty task.
Incorrect. Scaling an invalid measurement does not repair missing input.
Correct. Both methods must process the same logical data.
Problem 12
A proof gives initialization and termination but never shows preservation. What remains?
Only choose a faster language
Show every update keeps the invariant true
Nothing if one sample passed
Answer and reasoning for every option
Best answer: B
Incorrect. Implementation language does not supply the missing argument.
Correct. The loop may break the claimed property before termination.
Incorrect. One sample cannot establish all updates.