Sponsored
Sponsored
Solve with full IDE support and test cases
This approach involves using bit manipulation to find out which bits are different between the XOR of the array and k. For each differing bit, calculate the minimum number of flips needed across all elements to switch that bit in the resultant XOR.
Time Complexity: O(n), where n is the length of the array, since we only traverse it twice.
Space Complexity: O(1), as no additional data structures are used.
1def minOperations(nums, k):
2 xor_sum = 0
3 for num in nums:
4 xor_sum ^= num
5 diff = xor_sum ^ k
6 operations = 0
7 while diff != 0:
8 operations += diff & 1
9 diff >>= 1
10 return operations
11
12# Example usage
13nums = [2, 1, 3, 4]
14k = 1
15print(minOperations(nums, k))
16
This Python solution follows the same logic. We compute the XOR of the array and then XOR it with k to find the number of different bits.
In this approach, the focus is on counting the set bits of two numbers (XOR sum and k) - i.e., how many bits are 1 in their binary representation. We aim to equalize the set bits count by flipping specific bits in nums.
Time Complexity: O(n + log(max(nums[i])))
Space Complexity: O(1).
1
We define a helper function to count the set bits of a number. We calculate XOR sum first, and then find the difference in set bit numbers compared to k.