Minimum Number of Operations to Make Array XOR Equal to K

You are given a 0-indexed integer array nums and a positive integer k.

You can apply the following operation on the array any number of times:

  • Choose any element of the array and flip a bit in its binary representation. Flipping a bit means changing a 0 to 1 or vice versa.

Return the minimum number of operations required to make the bitwise XOR of all elements of the final array equal to k.

Note that you can flip leading zero bits in the binary representation of elements. For example, for the number (101)2, you can flip the fourth bit and obtain (1101)2.

Example 1
Inputnums = [2,1,3,4], k = 1
Output2
After two bit flips, the final array can become [6, 1, 2, 4], whose XOR is 1, and it cannot be done in fewer operations.
Example 2
Inputnums = [2,0,2,0], k = 0
Output0
The XOR of the array is already 0, so no operation is needed.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^6
  • 0 <= k <= 10^6

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate