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.
1function minOperations(nums, k) {
2 let xorSum = 0;
3 nums.forEach(num => {
4 xorSum ^= num;
5 });
6 let diff = xorSum ^ k;
7 let operations = 0;
8 while (diff !== 0) {
9 operations += diff & 1;
10 diff >>= 1;
11 }
12 return operations;
13}
14
15const nums = [2, 1, 3, 4];
16const k = 1;
17console.log(minOperations(nums, k));
JavaScript uses similar logic by looping over the array and calculating the XOR difference with k to count necessary bit flips.
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
For Java, the solution follows the same structure, utilizing the helper to find set bits and calculate the difference in count.