Python 0991.py
class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
# try to make target smaller/equal to startValue
steps = 0
while startValue < target:
steps += 1
# perform operations in reverse
if target & 1:
target += 1
else:
target //= 2
# the only way to reach smaller numbers is by painfully subtracting 1
steps += startValue - target
return steps
Difficulty
and has an acceptance rate of about 56% (200k+ submissions).
Typical patterns to solve this problem:
- Greedy
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method brokenCalc that computes the minimum number of operations required to transform an integer startValue into another integer target. The algorithm works by reasoning backwards from target toward startValue, applying the inverse of the allowed forward operations. This reverse approach reduces the search space dramatically and yields an optimal count of steps.
Core Logic
Initialization
steps = 0
A counter steps is created to accumulate the number of operations performed during the reverse traversal.
Reverse Traversal Loop
while startValue < target:
steps += 1
if target & 1:
target += 1
else:
target //= 2
The loop continues as long as the current target exceeds startValue. Each iteration represents one reverse operation, and the counter is incremented accordingly.
- The condition
target & 1checks the least-significant bit to determine whethertargetis odd. - If
targetis odd, the reverse of a forward “add 1” operation is applied by incrementingtarget(making it even). - If
targetis even, the reverse of a forward “multiply by 2” operation is applied by halvingtarget.
By repeatedly applying these inverse steps, the algorithm drives target down toward startValue in the fewest possible moves.
Final Adjustment
steps += startValue - target
return steps
When the loop exits, target is less than or equal to startValue. The only remaining forward operation that can reduce startValue to reach target is subtraction of 1. The difference startValue - target therefore represents the exact number of required “subtract 1” steps, which are added to the total count before returning.
Edge Cases Handled
When startValue is already greater than or equal to target, the while loop is bypassed entirely. In this situation the algorithm directly computes the difference startValue - target, which corresponds to the necessary number of decrement operations. This covers cases such as startValue == target (resulting in zero steps) and startValue > target (resulting in a positive step count).
If target is odd during the reverse process, the algorithm adds one to make it even before halving. This ensures that the division step is always valid and avoids infinite loops that could arise from repeatedly encountering odd numbers.
Performance Optimizations
The reverse-search strategy eliminates the need for exhaustive forward exploration. By always choosing the operation that most rapidly reduces the distance to startValue-halving when possible and otherwise incrementing to enable halving-the method converges in logarithmic iterations relative to the magnitude of target.
The use of a bitwise AND (target & 1) to test oddness is a low-overhead operation compared to modulus, contributing to faster execution. Additionally, the algorithm performs only integer arithmetic, avoiding any costly data structures or recursion overhead.
Overall, the implementation achieves the minimal number of steps with a tight loop and constant-time arithmetic, making it highly efficient for large input values.
ELI5 - Simplified Explanation
Imagine a little robot that wants to reach a specific number. Sometimes the robot can double its current number to get bigger, and sometimes it can subtract one to get smaller. This code works like a puzzle where it tries to go backward from the goal number to the starting number to find the shortest path.
The robot looks at the target number and checks if it is an even or odd number. If the number is odd, it adds one because that makes it even. Once the number is even, the robot cuts the number in half. By going backward and shrinking the big target number, the robot can see how many steps were taken.
If the target number becomes smaller than the starting number, the robot just counts how many ones are left to subtract until it finally reaches the exact start. Every time the robot changes the number, it adds one to the count of steps. This keeps going until the numbers match up perfectly.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| Progiez | C++ | Python | Java | |||||||
| github | begeekmyfriend | C | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| fsq | C++ | |||||||||
| Garvit244 | Python | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| martianoff | Scala | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| begeekmyfriend | C | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| fsq | C++ | |||||||||
| Garvit244 | Python | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| martianoff | Scala | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 650: 2 Keys Keyboard
- problem 2749: Minimum Operations to Make the Integer Zero
Solved On The Same Day
- problem 1217: Minimum Cost to Move Chips to The Same Position
- problem 1221: Split a String in Balanced Strings
- problem 1323: Maximum 69 Number
- problem 1710: Maximum Units on a Truck
- problem 969: Pancake Sorting
- problem 1605: Find Valid Matrix Given Row and Column Sums
- problem 630: Course Schedule III
- problem 1425: Constrained Subsequence Sum
- problem 2147: Number of Ways to Divide a Long Corridor
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality