cs-075 — Partition by Parity
| Field | Value |
|---|---|
| id | cs-075 |
| difficulty | Intermediate |
| topics | invariants, partition |
| lecture | lecture-19 |
| estimated time | 5-minute attempt + 10-minute discussion |
| prerequisites | loops, lists, and tracing from lectures 1-6 |
| objective | choose the technique, trace it faithfully, and defend the boundary behaviour |
| solution | held by the instructor; discussed after the attempt |
Problem
Rearrange a list so evens precede odds, in-place. Two pointers from both ends with a loop invariant stated before code. Termination argument required.
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: [3, 1, 6, 2, 5] -> evens first: [6, 2, 3, 1, 5] (order within groups free)
- Output: in-place two-pointer partition; invariant: [0,l) even, (r,n-1] odd; terminates because the gap shrinks
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
- l advances past evens, r retreats past odds; when both stuck, swap and repeat - until l and r cross.
- 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: "Change one movement rule and predict the first input that breaks it."
Constraints and assumptions
- Difficulty: Intermediate (loops and lists assumed).
- Topics: invariants, partition.
- Classroom-scale inputs unless the problem says otherwise.
- Time-box: about five minutes for the plan and trace; finishing the details is a bonus, defending the method is the target.
- 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.