Moving the Wedding Cake

EasyrecursionAlso known as Tower of Hanoi

A bakery's wedding cake is built from separate round tiers, biggest at the bottom, each smaller than the one below. It sits on stand A, the photographer wants it on stand C, and stand B is a spare.

The tiers are heavy and soft. You can lift only one tier at a time, always a stand's top tier, and never set a tier on 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, in order, that gets the whole cake onto stand C.

Write each move as two letters: the stand you lift from, then the stand you place on. "AC" means: take A's top tier 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 the 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

With one tier, you lift it from A and place it on C, which takes 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 spare B, 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 for good.

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 breadth first until every tier is on C. That finds the shortest plan, but each tier can be on any of three stands: 3n states, 531,441 for 12 tiers.

It still finishes at this size, but it is heavy and hides the pattern. The plan itself has 2n − 1 moves, so nothing beats writing those down. A good solution does a fixed amount of work per move and uses almost no other memory.

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