AlgoFrames

Fewest operations

Standard · Write code · about 12 min

A number starts at start. One operation adds 1 to it or doubles it. Return the fewest operations that turn start into target.

Every number is a state and each operation is an edge. Values above target never help, so skip them.

Example 1

Input:

[2,9]

Output:

3

2 → 4 → 8 → 9.

Example 2

Input:

[3,3]

Output:

0

Already at the target.

Constraints

  • 1 ≤ start ≤ target ≤ 10000

Learn the idea first: Implicit graphs: grids, states and puzzles, a visual lesson.

More Implicit graphs: grids, states and puzzles problems