Python 0397.py
class Solution:
def integerReplacement(self, n: int) -> int:
if n == 1:
return 0
loops = set()
dp = set([ n ])
iterations = 0
while True:
iterations += 1
next = set()
for x in dp:
if x in loops:
continue
if x == 2: # x // 2 => 1 or x - 1 => 1
return iterations
loops.add(x)
if x % 2 == 0:
next.add(x // 2)
else:
next.add(x - 1)
next.add(x + 1)
dp = next
return -1
Difficulty
and has an acceptance rate of about 38% (400k+ submissions).
Typical patterns to solve this problem:
- Bit Manipulation
- Dynamic Programming
- Greedy
- Memoization
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 implementation solves the integer replacement problem by performing a breadth-first search (BFS) over the space of reachable integers. Starting from the input value n, each iteration expands the current frontier to the next set of candidates generated by the allowed operations (divide by 2 when even, otherwise add or subtract 1). The algorithm stops as soon as it reaches the value 1, returning the number of BFS layers traversed, which corresponds to the minimum number of steps required.
Core Logic
The entry point checks the trivial case where the input is already 1.
if n == 1:
return 0
A set named loops records every integer that has already been processed, preventing the algorithm from revisiting the same state. The current frontier is stored in dp, initially containing only the starting value.
loops = set()
dp = set([n])
iterations = 0
The main loop increments an iterations counter on each pass, representing the depth of the BFS.
while True:
iterations += 1
next = set()
for x in dp:
if x in loops:
continue
...
Inside the loop, the code first skips any value already present in loops. The special condition x == 2 is handled explicitly because from 2 the algorithm can reach 1 in a single additional step regardless of whether it chooses division or subtraction. Detecting this case allows an immediate return without generating the next frontier.
if x == 2: # x // 2 => 1 or x - 1 => 1
return iterations
After marking the current value as visited, the algorithm decides which successors to add to the next frontier. When the integer is even, the only optimal move is to halve it. When it is odd, both x - 1 and x + 1 are viable, and both are enqueued.
loops.add(x)
if x % 2 == 0:
next.add(x // 2)
else:
next.add(x - 1)
next.add(x + 1)
At the end of each BFS layer, the frontier dp is replaced with the newly constructed set next, and the loop repeats. The while True construct guarantees termination because the BFS explores all reachable states in increasing step count, and the early exit on x == 2 ensures that the algorithm never overshoots the target.
dp = next
A final return -1 is present as a safeguard, though execution never reaches it under normal circumstances.
Edge Cases Handled
The code explicitly handles the base case where the input equals 1, returning zero steps immediately. The condition x == 2 is another edge case; it captures the situation where the next operation will inevitably produce 1, allowing the function to terminate one iteration earlier than a generic check for x == 1. By storing processed values in loops, the implementation also gracefully handles cycles that could arise from repeatedly applying +1 and -1 on odd numbers, ensuring the search does not get stuck in an infinite loop.
Performance Optimizations
Using a set for both the visited collection (loops) and the current frontier (dp) provides O(1) average-time membership checks and insertions, which keeps each BFS expansion efficient. The early return on x == 2 cuts off a whole level of exploration that would otherwise be required to discover the final step, reducing the number of iterations for inputs that quickly converge to the value 2. By processing each frontier as a whole before moving to the next, the algorithm avoids redundant work and guarantees that the first time a value is reached corresponds to the minimal number of steps. The avoidance of duplicate entries through the loops set also limits the growth of the frontier, preventing unnecessary expansion of the search space.
ELI5 - Simplified Explanation
Imagine you have a big treasure chest filled with a special magic number. There is a game you want to play where you try to turn your big number into the number one by following two simple rules. If your number is even, you can cut it in half. If your number is odd, you can either take one away or add one to it.
The code works like a tiny robot that tries to reach the number one as fast as possible. Instead of just picking one path, the robot keeps track of every possible number it can reach during each step of the journey. It puts these numbers into a group and looks at all of them at the same time.
As the robot plays, it writes down every number it has already visited in a notebook so it does not get stuck going in circles. In each step, the robot asks if any of the numbers in its current group can become one. If it sees that a number is two, it knows that the very next move will land on one, so it counts how many steps it took to get there. It keeps jumping through these numbers, creating new groups of possibilities until the goal is found.
Code Quality
Complexity Analysis
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 | ||||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 257: Binary Tree Paths
- problem 551: Student Attendance Record I
- problem 605: Can Place Flowers
- problem 236: Lowest Common Ancestor of a Binary Tree
- problem 289: Game of Life
- problem 413: Arithmetic Slices
- problem 525: Contiguous Array
- problem 567: Permutation in String
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