You have a "broken" calculator that only has two buttons:
startValue and a targetValue, find the minimum number of operations to reach the target.Microsoft and Nutanix use this problem to test your ability to work "backwards" to find an optimal path. While it might look like a Breadth-First Search (BFS) problem, the state space is too large for BFS to be efficient. The problem is a great test of Greedy thinking—specifically, that it's often easier to divide the target by 2 than to multiply the start value.
The Greedy pattern is the most effective here, but you apply it from the targetValue back to the startValue.
targetValue is even, divide it by 2.targetValue is odd, add 1 to it.
Continue this until targetValue is less than or equal to startValue. Finally, the remaining steps are simply the difference between startValue and the current targetValue.startValue = 2, targetValue = 3
Working backwards from 3:
The most common mistake is trying to use BFS, which will run out of memory for large target values. Another error is trying to work forward from startValue to targetValue with greedy choices, which is much more difficult to get right. Working backwards simplifies the decision tree significantly.
If a problem involves doubling and subtracting, always try working backwards. Division is a much more restrictive operation than multiplication, which often narrows down the optimal path and makes the greedy choice obvious.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Smallest Number With Given Digit Product | Medium | Solve | |
| Maximum Swap | Medium | Solve | |
| Max Difference You Can Get From Changing an Integer | Medium | Solve | |
| Determine the Minimum Sum of a k-avoiding Array | Medium | Solve | |
| Find the Minimum Number of Fibonacci Numbers Whose Sum Is K | Medium | Solve |