Taro Logo

Number of Bit Changes to Make Two Integers Equal

#1 Most AskedEasy
Topics:
Bit Manipulation

You are given two positive integers n and k.

You can choose any bit in the binary representation of n that is equal to 1 and change it to 0.

Return the number of changes needed to make n equal to k. If it is impossible, return -1.

Example 1:

Input: n = 13, k = 4

Output: 2

Explanation:
Initially, the binary representations of n and k are n = (1101)2 and k = (0100)2.
We can change the first and fourth bits of n. The resulting integer is n = (0100)2 = k.

Example 2:

Input: n = 21, k = 21

Output: 0

Explanation:
n and k are already equal, so no changes are needed.

Example 3:

Input: n = 14, k = 13

Output: -1

Explanation:
It is not possible to make n equal to k.

Constraints:

  • 1 <= n, k <= 106

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values for integers `n` and `k`? Can they be negative, or are we strictly dealing with non-negative integers?
  2. Could you clarify the condition under which it is considered "impossible" to make `n` equal to `k`, resulting in `-1`?
  3. Are we allowed to flip a bit in `n` from `1` to `0`, but strictly prohibited from flipping a `0` to a `1` (or vice versa), or does "bit changes" allow both directions freely?
  4. What data types are `n` and `k` represented as? Should I expect standard 32-bit signed integers, or could they be 64-bit integers or arbitrary-length representations?
  5. If `n` and `k` are already equal, should the function correctly return `0` modifications?

Brute Force Solution

Approach

To convert the first integer to the second integer, we can only flip bits that are currently set to one into zero. This means that every bit set in the target integer must also be set in the initial integer. If this condition is satisfied, the answer is simply the number of set bits in the initial integer that are not set in the target integer.

Here's how the algorithm would work step-by-step:

  1. Verify whether all set bits in the target integer are present in the source integer using bitwise AND.
  2. Return negative one immediately if the target requires any bit that is zero in the source.
  3. Calculate the exclusive OR of the source and target to find all bit positions where they differ.
  4. Count and return the total number of set bits in this difference.

Code Implementation

def min_changes(source_num, target_num):
    # Check if target has any set bit where source does not
    if (source_num & target_num) != target_num:
        return -1
    # Count the number of bits that need to be changed from 1 to 0
    diff_bits = source_num ^ target_num
    # Return the total count of set bits in the difference
    return bin(diff_bits).count("1")

Big(O) Analysis

Time Complexity
O(1) – The integers are bounded up to 10^6, which takes at most 20 bits, making bitwise operations and bit counting run in constant time.
Space Complexity
O(1) – Only a couple of intermediate values are stored, consuming a constant amount of extra memory.

Optimal Solution

Approach

The problem asks for the number of bits to change from 1 to 0 in order to transform one integer into another. We can only turn bits from 1 to 0, which means any set bit in the target must already be set in the original number. If this condition is met, the answer is simply the count of bits that are 1 in the original number but 0 in the target.

Here's how the algorithm would work step-by-step:

  1. Verify whether all set bits of the target integer are also set in the original integer using a bitwise AND operation.
  2. Return -1 immediately if the target contains set bits that are missing in the original integer.
  3. Calculate the bitwise XOR between the two integers to isolate the positions where bits differ.
  4. Count the number of set bits in the resulting XOR mask.
  5. Return the count as the minimum number of bit changes required.

Code Implementation

def min_changes(number_n, number_k):
    # Check if number_k has any set bits that are not present in number_n
    if (number_n & number_k) != number_k:
        return -1
    # Count the bits that need to be turned off from number_n
    difference_mask = number_n ^ number_k
    # Return the total number of set bits that differ
    return bin(difference_mask).count("1")

Big(O) Analysis

Time Complexity
O(1) – The bitwise operations and bit counting execute in constant time because integers up to 10^6 are bounded by at most 20 bits.
Space Complexity
O(1) – Only a few auxiliary integer variables are used, requiring a fixed amount of additional memory.

Edge Cases

Both integers n and k are equal
How to Handle:
The XOR operation results in zero, correctly returning a bit change count of zero.
Negative integers provided as inputs
How to Handle:
Integers are treated using their standard two-complement binary representation, seamlessly handling sign bits.
Zero values for n or k
How to Handle:
Bitwise operations handle zero natively by comparing individual bit positions against standard integer widths.
Maximum 32-bit or 64-bit integer limits
How to Handle:
Bitwise operators natively process full-width primitive integers without causing overflow issues.
Cases where it is impossible to transform n into k
How to Handle:
Since any bit in n can be flipped to match k, a valid solution always exists and impossible cases do not occur.
0/3 completed