Python 1611.py
class Solution:
# breadth-first search, too slow for large numbers
def bruteforce(self, n: int) -> int:
dp = set([ n ])
steps = 0
while True:
next = set()
for x in dp:
if x <= 1: # 0 => done
return steps + x # 1 => done in next iteration
# clear rightmost bit
next.add(x ^ 1)
# find rightmost set bit
mask = 1
while (x & mask) == 0:
mask <<= 1
# clear its left neighbor
mask <<= 1
next.add(x ^ mask)
dp = next
steps += 1
def minimumOneBitOperations(self, n: int) -> int:
# brute-forcing the problem for small numbers gives the sequence
# 1, 3, 2, 7, 6, 4, 5, 15, 14, 12, 13, 8, 9, 10, 11, 31, 30, 28, 29, ...
# which is part of OEIS: https://oeis.org/A006068
# they even have a O(log2(n)) Python script to compute this sequence
#for i in range(1, 20):
# print(i, self.bruteforce(i))
# originally by Indranil Ghost / Joerg Arndt
s = 1
while True:
shifted = n >> s
if shifted == 0:
break
n ^= shifted
s <<= 1
return n
Difficulty
and has an acceptance rate of about 73% (80k+ submissions).
Typical patterns to solve this problem:
- Bit Manipulation
- Dynamic Programming
- 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 module defines a Solution class that solves the “minimum one-bit operations” problem. Two public methods are present: bruteforce, which explores the state space using breadth-first search, and minimumOneBitOperations, which implements a compact logarithmic-time algorithm derived from known mathematical properties of the sequence. The bruteforce method is primarily illustrative; the core solution resides in the bit-manipulation loop of minimumOneBitOperations.
Key Steps
The bruteforce method initializes a set containing the starting integer n. It then iteratively expands the frontier of reachable numbers by applying two elementary operations: clearing the least-significant bit and clearing the bit immediately to the left of the rightmost set bit. The loop terminates when a value of 0 or 1 is encountered, returning the accumulated step count.
dp = set([ n ])
steps = 0
while True:
next = set()
for x in dp:
if x <= 1:
return steps + x
next.add(x ^ 1) # clear rightmost bit
mask = 1
while (x & mask) == 0:
mask <<= 1
mask <<= 1
next.add(x ^ mask) # clear left neighbor of rightmost set bit
dp = next
steps += 1
The minimumOneBitOperations method replaces the exhaustive search with a deterministic transformation. It repeatedly right-shifts the current value of n by an ever-increasing power of two, XOR-ing the shifted result back into n. The loop stops when the shifted value becomes zero, at which point n holds the minimal operation count.
s = 1
while True:
shifted = n >> s
if shifted == 0:
break
n ^= shifted
s <<= 1
return n
The algorithm leverages the observation that the target sequence follows a Gray-code-like pattern, allowing each iteration to eliminate a block of higher-order bits in a single step.
Edge Cases
When the input n equals 0, the bruteforce loop immediately satisfies the x <= 1 condition, returning steps + x, which evaluates to 0. This correctly reflects that no operations are required. For n equal to 1, the same condition triggers a return of steps + 1, yielding 1, the expected minimal count because a single clear-rightmost-bit operation suffices.
The minimumOneBitOperations method also handles these cases gracefully. With n = 0, the first right shift yields 0, causing the loop to break without modifying n; the final return yields 0. With n = 1, the shifted value becomes 0 on the first iteration, the loop exits, and n remains 1, which is the correct answer.
Large integers are accommodated because the loop’s termination condition depends solely on the shifted value reaching zero. As s doubles each iteration, the number of iterations grows logarithmically with the position of the most significant set bit, ensuring that even values near the maximum size of Python’s arbitrary-precision integers are processed efficiently.
Performance Optimizations
The transition from breadth-first search to the bit-wise reduction loop eliminates exponential state growth. By directly manipulating the binary representation, the algorithm avoids constructing intermediate sets and performing membership checks, which are costly in both time and memory.
The use of a single variable s that doubles each iteration (s <<= 1) reduces the number of shift operations required to reach the most significant bit. Each iteration processes a whole block of bits rather than a single bit, collapsing the work needed to compute the result.
XOR (^=) is employed to toggle bits in place, avoiding the creation of new integer objects for intermediate values. This in-place update contributes to lower allocation overhead and better cache locality.
Overall, the method achieves a compact, deterministic computation that scales with the binary length of the input rather than its numeric magnitude, delivering rapid results for the full range of permissible inputs.
ELI5 - Simplified Explanation
Imagine that numbers are like special patterns made of tiny light switches that can be either on or off. Sometimes you want to turn all the lights off, but you have a strict rule about which switches you can flip. You can always flip the very first switch on the right side. However, if you want to flip any other switch, the one right next to it must be turned on first.
The code works like a clever helper trying to turn all those switches off in the fewest moves possible. It looks at the whole row of switches and decides how to turn them off one by one by sliding through the pattern. Instead of trying every single possibility, which would take a very long time, it uses a shortcut.
The computer looks at the pattern and sees if it can combine the switches in a special way to skip over the long process. It keeps shifting the pattern and mixing it with itself until all the lights are finally dark. It is like solving a complicated puzzle by noticing a repeating trick that lets you jump straight to the finish line instead of counting every single tiny step along the way.
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++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Go | Python | Rust | TS | |||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 2009: Minimum Number of Operations to Make Array Continuous
- problem 2546: Apply Bitwise Operations to Make Strings Equal
Solved On The Same Day
- problem 464: Can I Win
- problem 729: My Calendar I
- problem 1286: Iterator for Combination
- problem 1348: Tweet Counts Per Frequency
- problem 1387: Sort Integers by The Power Value
- problem 2424: Longest Uploaded Prefix
- problem 327: Count of Range Sum
- problem 699: Falling Squares
- problem 1553: Minimum Number of Days to Eat N Oranges
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