Broken Calculator - Problem
Broken Calculator Problem: You have a malfunctioning calculator that starts with an integer
๐ข Multiply by 2: Double the current number
โ Subtract 1: Decrease the current number by 1
Your goal is to transform
Example: If
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
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
โก Linearithmic
Space Complexity
O(1)
Only uses a constant amount of extra space for variables
โ Linear Space
Constraints
- 1 โค startValue, target โค 109
- Both startValue and target are positive integers
- Time limit: 1 second per test case
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code