Moving the Wedding Cake

EasyrecursionAlso known as Tower of Hanoi

A bakery has finished a wedding cake built from separate round tiers, the biggest at the bottom and each tier smaller than the one under it. It sits on stand A, and the photographer wants it on stand C. There is one empty spare stand, B.

The tiers are heavy and soft. You can lift only one tier at a time, always the top tier of a stand, and you may never set a tier on top of a smaller one, or it gets crushed. Plan the move.

Your task

Write moveCake(tiers). The cake has tiers tiers, all on stand A. Return the list of moves that gets the whole cake onto stand C, in the order you make them.

Write each move as two letters: the stand you lift from, then the stand you put the tier on. "AC" means: take the top tier of A and place it on C. Every move must be legal (lift from a stand that has a tier, never place a tier on a smaller one), and your list must use the fewest moves possible. With 0 tiers, return an empty list.

moveCake(tiers: int) → string[] Several answers can be correct; any valid one is accepted.

Examples

Example 1
Input
tiers = 1
Output
["AC"]
Why

One tier: lift it from A and put it on C. One move.

Example 2
Input
tiers = 2
Output
["AB", "AC", "BC"]
Why

The big tier cannot go to C while the small one sits on it. So the small tier goes to the spare stand B first, the big tier goes A → C, and the small tier goes from B onto it. Putting the small tier on C first would block C, because the big tier can never sit on it.

Constraints

  • 0 ≤ tiers ≤ 12
  • Stands are named "A" (start), "B" (spare) and "C" (goal).
  • The shortest plan is unique, so there is exactly one correct list.
Start with brute force

Treat every arrangement of tiers on the three stands as a state and search them all, breadth first, until every tier is on C. That finds the shortest plan, but each tier can be on any of three stands, so there are 3n arrangements to store: 531,441 for 12 tiers.

At this size the search still finishes, but it is heavy and it hides the pattern. The plan itself has 2n − 1 moves, so nothing can be faster than writing those down. Aim for a method that spends a fixed amount of work per move and remembers almost nothing else.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code