cs-043 — Rotate and Roll
| Field | Value |
|---|---|
| id | cs-043 |
| difficulty | Intermediate |
| topics | lists, rotation |
| lecture | lecture-11 |
| 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
Rotate a list by k positions (left or right) without extra library calls. Handle k larger than the length; connect rotation to slicing.
Your deliverable is the rearranged list for the worked instance, the slice arithmetic, and a note on what aliasing would change. 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: [1, 2, 3, 4, 5], rotate left by 2; rotate right by 2
- Output: left 2: [3, 4, 5, 1, 2]; right 2: [4, 5, 1, 2, 3]
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
- Right rotation by k is left rotation by n-k. One slice helper, two calls.
- Slices are half-open: they make boundaries explicit instead of hidden in loop conditions.
- Aliasing is the difference between copying a list and copying a name.
Discussion starter
After the solution is revealed, the class spends five minutes on this prompt: "Find the smallest change to the task that makes the slice solution wrong."
Constraints and assumptions
- Difficulty: Intermediate (loops and lists assumed).
- Topics: lists, rotation.
- 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: Convert your in-place solution to a copying one and compare the trade-offs.