Broken Calculator - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: startValue = 2, target = 3
Output: 2
💡 Note: Use operations: 2 × 2 = 4, then 4 - 1 = 3. Total: 2 operations
Example 2 — Target Smaller
$ Input: startValue = 5, target = 8
Output: 2
💡 Note: Use operations: 5 - 1 = 4, then 4 × 2 = 8. Total: 2 operations
Example 3 — Only Subtraction
$ Input: startValue = 3, target = 10
Output: 3
💡 Note: Working backwards: 10÷2=5, 5+1=6, 6÷2=3. Total: 3 operations

Constraints

  • 1 ≤ startValue, target ≤ 109

Visualization

Tap to expand
Broken Calculator - Reverse Greedy Approach INPUT 2 startValue 3 target Available Operations: x * 2 x - 1 startValue = 2 target = 3 ALGORITHM STEPS 1 Work Backwards Start from target (3) 2 Reverse Operations x*2 becomes x/2 x-1 becomes x+1 3 Greedy Choice If even: divide by 2 If odd: add 1 4 Stop Condition When target <= start Execution Trace: target=3 (odd) +1 --> 4 ops=1 target=4 (even) /2 --> 2 ops=2 target=2 == start [OK] FINAL RESULT Forward Path Found: 2 start *2 4 -1 3 target Total Operations: 2 Breakdown: 1 multiply 1 subtract Output: 2 [OK] Minimum ops found Key Insight: Working backwards from target is more efficient because the reverse operations have clear greedy choices: - If target is even, dividing by 2 is always optimal (reverse of multiply) - If target is odd, we must add 1 first (reverse of subtract). Time: O(log target), Space: O(1) TutorialsPoint - Broken Calculator | Reverse Greedy Approach
Asked in
Google 25 Amazon 20 Microsoft 15
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen