Problem 1611

Abstract / Summary

Turn each number to zero by flipping its set bits one by one.

Note

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

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
43 lines | 1403 bytes | submitted September 29, 2023 | GitHub   50% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (80k+ submissions).

Typical patterns to solve this problem:
  • Bit Manipulation
  • Dynamic Programming
  • Memoization
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 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.

written by openai gpt

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.

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 = 7 | μ = 6.48 | σ = 1.57

Complexity Analysis

not analyzed yet

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++ 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++
25 links | 13 authors | 8 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

6 medium 3 hard
10 solutions   September 29, 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