CS 201 — Data Structures, Algorithms and Systems · Weeks 1–2
Specifications, correctness and growth rates
Full teaching sequence and cumulative subject work
Preparation: study 0.2–0.4 and 3.1–3.2: statements, sets, functions, logic and proof in the complete on-site Levin text. Attempt the investigation, work at least four exercises of increasing difficulty in each assigned section, and compare the selected hints/solutions only after a written attempt. Then complete the algorithm reading and implement the unit laboratory. For each algorithm give a specification, trace, correctness argument and time/space analysis.
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 reasoning
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 transfer solution
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.
Learning objectives
- Explain and trace the mechanisms in specifications, correctness and growth rates.
- Apply the method to the worked example and changed-condition exercise.
- Identify assumptions, failure cases and the evidence needed to justify a result.
Study the mechanism
An algorithm is a finite, precise procedure for a specified family of inputs. Correctness and efficiency are separate questions: a fast wrong answer is still wrong. State the precondition, postcondition and input-size measure before comparing methods. For a list search, n can be the number of records; for a graph, both vertices and edges matter.
Asymptotic analysis describes how resource use grows, suppressing constant factors and smaller-order terms. O(n) is an upper-bound description, not an exact time measurement or a claim that an algorithm always scans all records. A linear search can finish immediately when the target is first and require n comparisons when absent. Worst-case, average-case and best-case claims therefore need labels. Timing a single small input cannot establish a growth law. Hardware, caching and interpreter overhead affect measured times; use counting and measurement together.
Correctness arguments often use invariants. Before each search iteration, every earlier position has been checked and does not match. Returning the current index gives a match; reaching the end establishes absence under the equality rule. The rule itself matters: case-insensitive names, unique identifiers and approximate numeric matches are different specifications.
Worked example
def find(items, target):
for i, item in enumerate(items):
if item == target:
return i
return None
assert find([8, 3, 8], 8) == 0
assert find([], 8) is NoneThe implementation returns the first matching index, not every occurrence. None distinguishes absence from index zero. Testing if find(...) would mistakenly treat a valid zero index as false. An absent target requires examining the whole finite list. Doubling a long absent-search input roughly doubles comparisons, though measured runtime may fluctuate.
Check your understanding
What is wrong with treating an O(n) bound as exactly n milliseconds?
- It confuses an asymptotic bound with measured time
- Nothing; big O includes the computer speed
- Only sorted inputs can use big O
Answer and reasoning for every option
Correct: It confuses an asymptotic bound with measured time Growth rates suppress units and implementation constants.
Reconsider: Nothing; big O includes the computer speed Big O does not encode hardware or milliseconds.
Reconsider: Only sorted inputs can use big O Sorted and unsorted algorithms can both be analyzed.
Transfer laboratory: An operation-count crossover
A scan costs n comparisons per absent query. Building a sorted index costs n log2 n comparison units and each binary search costs log2 n. Under this simplified model, compare 1 and 1000 queries when n=1024.
Work through the full solution
Here log2 n=10. One scan costs 1024 units, while building and searching costs 10240+10=10250. For 1000 queries scans cost 1024000; indexed work costs 10240+10000=20240. The crossover solves 1024q>10240+10q, or q>10.099, so the integer threshold is 11. These abstract counts omit constants, memory and maintenance; measurement is still needed.
Evidence of understanding
Include construction cost, derive the crossover and label the simplifying assumptions.
Complete on-site teaching readings
These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.
- 1 . Introduction · Pat Morin
- 1 . 1 The Need for Efficiency · Pat Morin
- 1 . 2 Interfaces · Pat Morin
- 1 . 3 Mathematical Background · Pat Morin
- 1 . 4 The Model of Computation · Pat Morin
- 1 . 5 Correctness, Time Complexity, and Space Complexity · Pat Morin
- 1 . 6 Code Samples · Pat Morin
- 1 . 7 List of Data Structures · Pat Morin
- 1 . 8 Discussion and Exercises · Pat Morin
Open the complete practice sequence and cumulative assessment →