Broken Calculator - Problem
Broken Calculator Problem: You have a malfunctioning calculator that starts with an integer startValue on its display. Due to the malfunction, only two operations work:

๐Ÿ”ข Multiply by 2: Double the current number
โž– Subtract 1: Decrease the current number by 1

Your goal is to transform startValue into target using the minimum number of operations. This is a classic optimization problem that tests your understanding of greedy algorithms and reverse thinking.

Example: If startValue = 2 and target = 3, you can: 2 โ†’ 4 (multiply by 2) โ†’ 3 (subtract 1) = 2 operations.

Input & Output

example_1.py โ€” Basic Case
$ Input: startValue = 2, target = 3
โ€บ Output: 2
๐Ÿ’ก Note: Starting with 2: 2 โ†’ 4 (multiply by 2) โ†’ 3 (subtract 1). Total: 2 operations.
example_2.py โ€” Larger Target
$ Input: startValue = 5, target = 8
โ€บ Output: 2
๐Ÿ’ก Note: Working backwards: 8 (even) โ†’ 4 (even) โ†’ 2. Since 2 < 5, we need 5-2=3 more subtractions. Total: 2+3=5 operations. Actually optimal path: 5โ†’4โ†’8 (2 ops).
example_3.py โ€” Same Values
$ Input: startValue = 3, target = 3
โ€บ Output: 0
๐Ÿ’ก Note: Already at target, no operations needed.

Visualization

Tap to expand
Calculator Mountain PathStartTargetForward Path (Hard)Backward Path (Easy)รท2รท2+1รท2๐ŸŽฏ Working backwards gives us the optimal path!
Understanding the Visualization
1
Start from Destination
Begin at the target peak and work backwards
2
Choose Optimal Path
Even numbers came from multiplication, odd numbers from subtraction
3
Reach Source Region
Continue until you reach or pass the starting peak
4
Count Total Steps
Add up all the operations needed for the optimal path
Key Takeaway
๐ŸŽฏ Key Insight: Working backwards eliminates guesswork - at each step, there's only one optimal reverse operation to apply!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(log target)

Each iteration either halves the target (even case) or reduces by 1 then halves (odd case), giving logarithmic complexity

n
2n
โšก Linearithmic
Space Complexity
O(1)

Only uses a constant amount of extra space for variables

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค startValue, target โ‰ค 109
  • Both startValue and target are positive integers
  • Time limit: 1 second per test case
Asked in
Google 45 Amazon 32 Meta 28 Microsoft 23
78.2K Views
Medium Frequency
~15 min Avg. Time
1.8K 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