Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1611. Minimum One Bit Operations to Make Integers Zero - Leetcode Solution

Code Implementation

class Solution:
    def minimumOneBitOperations(self, n: int) -> int:
        res = 0
        while n:
            msb = n.bit_length() - 1
            res ^= (1 << msb)
            n ^= (1 << msb)
        return res
      
class Solution {
public:
    int minimumOneBitOperations(int n) {
        int res = 0;
        while (n) {
            int msb = 31 - __builtin_clz(n);
            res ^= (1 << msb);
            n ^= (1 << msb);
        }
        return res;
    }
};
      
class Solution {
    public int minimumOneBitOperations(int n) {
        int res = 0;
        while (n != 0) {
            int msb = 31 - Integer.numberOfLeadingZeros(n);
            res ^= (1 << msb);
            n ^= (1 << msb);
        }
        return res;
    }
}
      
var minimumOneBitOperations = function(n) {
    let res = 0;
    while (n !== 0) {
        let msb = 31 - Math.clz32(n);
        res ^= (1 << msb);
        n ^= (1 << msb);
    }
    return res;
};
      

Problem Description

You are given a non-negative integer n. Your goal is to transform n into 0 using the minimum number of special bit operations. In one operation, you can choose any bit position i (where i > 0) and flip both the i-th and (i-1)-th bits of n (from 0 to 1 or 1 to 0).

Return the minimum number of such operations required to make n equal to 0.

  • Each operation flips exactly two adjacent bits.
  • You may not reuse the same operation sequence for a different bit pair.
  • There is always a valid solution for any non-negative integer n.

Thought Process

At first glance, this problem seems like it could be solved by simply flipping bits from left to right or right to left. However, since each operation flips two adjacent bits, flipping one bit can affect another, and operations may need to be carefully sequenced to avoid undoing previous work.

A brute-force approach would try all possible sequences of operations, but this quickly becomes infeasible for large numbers due to exponential growth in possibilities. This suggests we need to look for a pattern or mathematical property that can help us compute the answer directly.

Observing how the operation works, we can see that it is similar to the Gray code transformation, where each number differs from the previous by only one bit. This insight allows us to relate the problem to properties of Gray codes and use their mathematical structure to optimize our solution.

Solution Approach

To solve this problem efficiently, we use the following strategy:

  1. Gray Code Relationship: The minimum number of operations required to reduce n to 0 is equal to the inverse Gray code of n. The Gray code of a number x is x ^ (x >> 1). The inverse process, which reconstructs the original number from its Gray code, can be computed iteratively.
  2. Iterative Calculation: Initialize a result variable res to 0. While n is not zero, find the most significant bit (MSB) that is set. Toggle res at the MSB position, then flip off that bit in n. Repeat until n is zero.
  3. Why This Works: Each bit flip corresponds to a Gray code operation. By toggling the MSB and reducing n accordingly, we accumulate the minimum number of required operations.
  4. Implementation Choices:
    • We use bit manipulation to efficiently find the MSB and perform the necessary flips.
    • All operations are O(1) for each bit, leading to a fast solution.

Example Walkthrough

Let's walk through an example with n = 6 (which is 110 in binary):

  1. Initial: n = 110, res = 0
  2. Step 1: MSB is at position 2 (counting from 0). Toggle res ^= 100 (4), so res = 4. Then, n ^= 100 (n = 010, which is 2).
  3. Step 2: MSB is at position 1. Toggle res ^= 10 (2), so res = 6. Then, n ^= 10 (n = 0).
  4. Done: n = 0, so we return res = 6.

This matches the expected minimum number of operations for n = 6.

Time and Space Complexity

  • Brute-force approach: Would have exponential time complexity, as it would need to explore all possible sequences of operations, which is not feasible for large n.
  • Optimized approach: The provided solution iterates once for each bit set in n. Since standard integers have at most 32 or 64 bits, the time complexity is O(log n) (specifically, proportional to the number of bits in n).
  • Space complexity: O(1), since we only use a constant number of variables.

Summary

This problem can be solved efficiently by recognizing its relationship to Gray codes. By using bit manipulation and the inverse Gray code transformation, we can compute the minimum number of special bit operations to reduce any integer n to zero. The approach avoids brute-force search, runs in logarithmic time, and uses constant space, making it both elegant and efficient.