Broken Calculator Problem
Description
LeetCode Problem 991.
There is a broken calculator that has the integer startValue on its display initially. In one operation, you can:
- multiply the number on display by 2, or
- subtract 1 from the number on display.
Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator.
Example 1:
Input: startValue = 2, target = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
Example 2:
Input: startValue = 5, target = 8
Output: 2
Explanation: Use decrement and then double {5 -> 4 -> 8}.
Example 3:
Input: startValue = 3, target = 10
Output: 3
Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.
Example 4:
Input: startValue = 1024, target = 1
Output: 1023
Explanation: Use decrement operations 1023 times.
Constraints:
- 1 <= x, y <= 10^9
Solution
Approach: Greedy, Working Backwards from target
Going forwards it is hard to tell when to double and when to subtract: 3 -> 6 -> 5 -> 10 subtracts in the middle. Going backwards from target to startValue, the choice becomes forced. The reverse operations are "halve" (allowed only on an even number) and "add 1".
While target > startValue:
- If
targetis odd, it cannot be the result of doubling, so the last forward step was a subtraction:target += 1. - If
targetis even, halve it:target /= 2.
Count each step. Once target <= startValue, halving would only take us further away, so the remaining startValue - target steps are all "add 1" (subtractions going forwards).
Why is halving an even target always right? The alternative is adding 1 an even number of times, say twice, before halving: (target + 2) / 2 takes 3 steps, while target / 2 + 1 reaches the same number in 2. In general, 2k additions followed by a halving can always be replaced by a halving followed by k additions, so halving first is never worse.
Example 3 backwards: 10 -> 5 -> 6 -> 3, three steps.
Complexity: O(log target) time, since target is halved at least every second step, and O(1) space.
class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
# Work backwards from target with the reverse operations: halve, or add 1.
operations = 0
while target > startValue:
if target % 2 == 0:
target //= 2
else:
target += 1 # an odd number cannot be the result of doubling
operations += 1
# Now target <= startValue: the rest is subtracting 1 going forwards.
return operations + (startValue - target)
Now write it from memory
Close the write-up and solve it yourself against the tests.