Parcel-delivery app~20 min2s · 256 MBtarget O(q × n) time, O(1) spacerecursion
A parcel hub has three bays, numbered 1, 2 and 3. At the start, n crates of different sizes are stacked in bay 1, with the largest at the bottom. A robot must move the whole stack to bay 3.
The robot moves one crate at a time to the top of a bay, and never puts a crate on a smaller one. The plan is recursive: move the n - 1 smaller crates to the spare bay, move the largest crate, then move the n - 1 crates on top of it. A supervisor asks about single moves of the plan.
Write crate_moves(n, ks).
n crates from bay 1 to bay 3, using bay 2 as the spare. Crates are numbered by size, from 1 (smallest) to n (largest).size crates has three parts. First comes the plan for size - 1 crates from source to spare. Then crate size moves from source to target. Last comes the plan for size - 1 crates from spare to target.k in ks, return [crate, from_bay, to_bay] for move number k of the plan. Moves are numbered from 1.k is between 1 and the number of moves in the plan, 2^n - 1.Input: n = 3, ks = [1, 2, 3, 4, 5, 6, 7]
Output: [[1, 1, 3], [2, 1, 2], [1, 3, 2], [3, 1, 3], [1, 2, 1], [2, 2, 3], [1, 1, 3]]Take n = 3. The plan has 7 moves.
| Move | Crate | From | To | Why |
|---|---|---|---|---|
| 1 | 1 | 1 | 3 | first sub-plan: crates 1 and 2 go to bay 2 |
| 2 | 2 | 1 | 2 | |
| 3 | 1 | 3 | 2 | |
| 4 | 3 | 1 | 3 | the largest crate moves |
| 5 | 1 | 2 | 1 | second sub-plan: crates 1 and 2 go to bay 3 |
| 6 | 2 | 2 | 3 | |
| 7 | 1 | 1 | 3 |
The answer lists all seven moves in order.
Input: n = 1, ks = [1]
Output: [[1, 1, 3]]One crate needs one move, from bay 1 to bay 3.
Input: n = 4, ks = [8, 9, 15]
Output: [[4, 1, 3], [1, 2, 3], [1, 2, 3]]The plan for 4 crates has 15 moves. Move 8 is the largest crate going from bay 1 to bay 3. Moves 9 and 15 belong to the second sub-plan.
1 ≤ n ≤ 501 ≤ ks.length ≤ 5,0001 ≤ ks[i] ≤ 2^n - 1The plan for 50 crates has 1,125,899,906,842,623 moves, so it cannot be played. But the recursion is only 50 levels deep. At each level, one comparison of k with the size of the first sub-plan tells which half holds move k.