KatInterview

Fewest Steps on a Faulty Calculator: Decrement or Double

Greedy & IntervalsAuto-graded · 24 test cases
MediumAuto-gradedGreedy & Intervalsgreedymathreverse-thinking

Last updated

Find the minimum number of decrement-by-one and double operations needed to turn one positive integer into another, which rewards working backward from the target with a greedy rule.

A calculator shows the positive integer start on its display. It has only two buttons:

  • Decrement: replace the displayed value x with x - 1.
  • Double: replace the displayed value x with 2 * x.

Each button press counts as one operation, and you may press the buttons in any order and any number of times.

Given the starting value start and the desired value target, return the minimum number of button presses needed to make the display show exactly target.

If start is already equal to target, the answer is 0.

Constraints

  • start and target are positive integers (at least 1).
  • Values can be large (up to about 10^9), so a search over every reachable value is too slow; aim for a solution that runs in logarithmic time in target.
  • Return a single integer.

Examples

Example 1

Input: fewest_button_presses(1, 2)

Output: 1

Example 2

Input: fewest_button_presses(9, 1)

Output: 8

Example 3

Input: fewest_button_presses(2, 10)

Output: 5

Example 4

Input: fewest_button_presses(100, 500)

Output: 41

Hints

Hint 1

Going forward from `start`, it is hard to tell whether to double now or to decrement first. Think about running the process in reverse, starting from `target`.

Hint 2

Reversed, a decrement becomes 'add 1' and a doubling becomes 'divide by 2' (only allowed when the value is even). If the current value is odd, which reverse move is forced? If it is even and still above `start`, which move is better?

Hint 3

Once the reversed value is no larger than `start`, halving no longer helps, and the remaining gap is closed by decrements alone, costing exactly `start - value`.