cs-074 — The Pair Sum Contract
| Field | Value |
|---|---|
| id | cs-074 |
| difficulty | Foundational |
| topics | two pointers, preconditions |
| lecture | lecture-19 |
| estimated time | 5-minute attempt + 10-minute discussion |
| prerequisites | lectures 1-2 (problem framing, precise pseudocode) |
| objective | recognise the pattern, translate it into precise steps, and trace it correctly |
| solution | held by the instructor; discussed after the attempt |
Problem
In a sorted list, find two elements summing to a target. The classic two-pointer; focus on the movement rule as an invariant, not a memorised trick.
Your deliverable is the result for the worked instance, the invariant in one sentence, and the termination argument. If the problem is ambiguous anywhere, state the assumption you are making and carry on — a stated assumption is part of a good answer.
Examples
- Input: sorted [1, 2, 4, 7, 11], target 15 -> 4+11; target 20 -> none
- Output: pair found (indices 3,4); none for 20; movement rule: sum small -> left++, sum big -> right--
Solve for the worked instance first. Then ask what would change if one number, name, or condition were replaced by something stranger.
What to notice
- Invariant: the answer pair, if it exists, always lies inside [l, r]. Each step discards one element safely.
- The invariant is the algorithm; the pointers are just bookkeeping.
- If you cannot say what strictly shrinks, the loop can spin forever.
Discussion starter
After the solution is revealed, the class spends five minutes on this prompt: "Restate the invariant in your own words — is yours strong enough to prove the answer?"
Constraints and assumptions
- Difficulty: Foundational (early-semester techniques assumed: precise statements, traces, simple loops).
- Topics: two pointers, preconditions.
- Classroom-scale inputs unless the problem says otherwise.
- Time-box: about five minutes; naming the pattern and stating the assumption is already a pass, completing the calculation is the stretch.
- Optional stretch (not required): describe an alternative approach and say when it beats the obvious one.
Hints and extension
- First nudge: identify the pattern the worked instance uses before computing anything.
- If stuck after three minutes, write the input/output line you expect and trace the smallest example by hand.
- After the reveal, attempt the extension below before the next lecture.
- Extension challenge: State the invariant in one sentence and point at the step that preserves it.