Broken Calculator — LeetCode 991 Python Solution

MediumGreedyMath
Problem
#991
Pattern
Greedy
Reading time
2 min

The 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.

Example

Input
startValue = 2, target = 3
Output
2
Explanation
Use double operation and then decrement operation {2 -> 4 -> 3}.

Python solution

Python
class Solution:
    def brokenCalc(self, startValue: int, target: int) -> int:
        ans = 0
        while startValue < target:
            if target & 1:
                target += 1
            else:
                target >>= 1
            ans += 1
        ans += startValue - target
        return ans

Complexity

MeasureComplexity
TimeO(\log n), where n is \textit{target}
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 991. Broken Calculator is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 991. Broken Calculator?
LeetCode 991. Broken Calculator is rated Medium on LeetCode.
What is the time complexity of LeetCode 991. Broken Calculator?
The Python solution on this page runs in O(\log n), where n is \textit{target}.
What is the space complexity of LeetCode 991. Broken Calculator?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 991. Broken Calculator cover?
LeetCode 991. Broken Calculator is tagged Greedy and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview