1563. Hanoi State After K

Hard7.5 points estimatedBrainteaserBit ManipulationRecursion

In the classic tower puzzle, n discs numbered 1..n (disc 1 is the smallest) all start stacked on peg 0, and the unique shortest sequence of moves carries the whole tower to peg 2, never putting a larger disc on a smaller one. That shortest sequence has exactly 2^n - 1 moves.

Given n and a move count k, return an int[] of length n whose entry at index d - 1 is the peg (0, 1 or 2) holding disc d immediately after the first k moves of that shortest sequence. With k = 0 every disc sits on peg 0.

Simulating up to 2^50 moves is impossible, so the intended solution reasons about each disc separately, using the fact that the disc d moves on every 2^d-th step, in a fixed cyclic order of pegs that depends on the parity of n - d. Target time O(n) and space O(1) beyond the output.

Example 1

Input:
n = 3, k = 0
Output:
[0,0,0]
Explanation:

No move has been made, so all three discs are still on peg 0.

Example 2

Input:
n = 3, k = 3
Output:
[1,1,0]
Explanation:

After 3 moves the pegs are [1, 1, 0] for discs 1, 2 and 3.

Example 3

Input:
n = 2, k = 3
Output:
[2,2]
Explanation:

All 3 moves are done, so both discs sit on peg 2.

Constraints

1 ≤ n ≤ 50; 0 ≤ k ≤ 2^n - 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…