Problem 991

Abstract / Summary

Given a start and target integer you can only double or add one each step find the fewest steps needed to reach the target from the start

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
15 lines | 511 bytes | submitted November 28, 2023 | GitHub   27% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 56% (200k+ submissions).

Typical patterns to solve this problem:
  • Greedy
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 & 1 checks the least-significant bit to determine whether target is odd.
  • If target is odd, the reverse of a forward “add 1” operation is applied by incrementing target (making it even).
  • If target is even, the reverse of a forward “multiply by 2” operation is applied by halving target.

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.93 | σ = 1.15

Complexity Analysis

Time: logarithmic
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
34 links | 21 authors | 9 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

10 solutions   November 28, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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