#991

Broken Calculator

Medium
MathGreedyGreedyMathematical Operations
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(n)
O(1)
💡

Intuition

Time O(log n)Space O(1)

Instead of starting from startValue and trying to reach target, we can reverse the problem. If we think about how we could have reached target, we can either divide by 2 (if target is even) or add 1 (if target is odd). This allows us to reduce the target towards the startValue efficiently.

⚙️

Algorithm

4 steps
  1. 1Step 1: While target is greater than startValue, check if target is even or odd.
  2. 2Step 2: If target is even, divide it by 2. If odd, increment it by 1 (to make it even).
  3. 3Step 3: Count each operation until target is less than or equal to startValue.
  4. 4Step 4: If target is less than startValue, add the difference to the operation count.
solution.py11 lines
1# Full working Python code
2
3def brokenCalculator(startValue, target):
4    operations = 0
5    while target > startValue:
6        if target % 2 == 0:
7            target //= 2
8        else:
9            target += 1
10        operations += 1
11    return operations + (startValue - target)

Complexity note: The time complexity is O(log n) because we are halving the target value in each step when it is even, which significantly reduces the number of operations needed.

  • 1Understanding the reverse operations can simplify the problem significantly.
  • 2Dividing by 2 is a powerful operation that reduces the problem size quickly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.