cs-085 — The Russian Dolls
| Field | Value |
|---|---|
| id | cs-085 |
| difficulty | Beginner |
| topics | recursion, base case |
| lecture | lecture-22 |
| estimated time | 5-minute attempt + 10-minute discussion |
| prerequisites | none |
| objective | state inputs, outputs, and assumptions, then solve a small instance by hand |
| solution | held by the instructor; discussed after the attempt |
Problem
Describe nested dolls recursively; write the function that counts layers. Base case and trust in the recursive call, made concrete.
Your deliverable is the recurrence with base cases, the answer for the worked instance, and the memoised (or tabulated) version. 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: doll with 5 layers
- Output: count_layers: 0 for no doll, else 1 + inner; base case is the whole lesson
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
- Write the base case in one sentence: 'a doll with nothing inside has 1 layer'.
- Trust the recursive call: if f(smaller) is correct, the transition is all you must get right.
- A DP table is the call tree, cached.
Discussion starter
After the solution is revealed, the class spends five minutes on this prompt: "Where does the memory go in the memoised version, and what is the trade?"
Constraints and assumptions
- Difficulty: Beginner (no prior experience assumed).
- Topics: recursion, base case.
- Classroom-scale inputs unless the problem says otherwise.
- Time-box: about five minutes for a first attempt; partial answers with clear reasoning are worth more than silent struggling.
- 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 the recursion to a loop and compare the call stacks.