call(back)
Algorithms & Data StructuresmediumSign in to star problems

Reach a Target With +2, Double and Halve

Starting from a positive integer a, the moves are +2, *2 (double) and /2 (halve, allowed only on an even number). Return any sequence of moves that reaches b, as a list of the strings "+2", "*2" and "/2"; an empty list when a === b. The grader replays your moves and checks the result; keep the sequence under 1000 moves.

reachTarget(3, 4)  ->  ["*2", "+2", "/2"]      // 3, 6, 8, 4
reachTarget(7, 2)  ->  ["*2", "+2", "/2", "/2", "/2"]   // 7, 14, 16, 8, 4, 2

Hints

Hint 1

+2 only reaches numbers of the same parity. To go from a to a + 1, double, add 2, and halve: 2a → 2a + 2 → a + 1.

Hint 2

To get smaller, reach a multiple of a power of two above the target and halve down. A breadth-first search over values up to about twice the larger number also finds a short path and is the easy correct answer.

Asked at