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.
1public class Solution {
2 public int minOperations(int[] nums, int k) {
3 int xorSum = 0;
4 for (int num : nums) {
5 xorSum ^= num;
6 }
7 int diff = xorSum ^ k;
8 int operations = 0;
9 while (diff != 0) {
10 operations += diff & 1;
11 diff >>= 1;
12 }
13 return operations;
14 }
15
16 public static void main(String[] args) {
17 Solution solution = new Solution();
18 int[] nums = {2, 1, 3, 4};
19 System.out.println(solution.minOperations(nums, 1));
20 }
21}
22
In Java, we iterate over the nums array to compute its XOR sum, then compute the XOR difference with k to count differing 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
For Java, the solution follows the same structure, utilizing the helper to find set bits and calculate the difference in count.