#2997

Minimum Number of Operations to Make Array XOR Equal to K

pupil · 400 · lc medium +24 · verified · 85.5% accepted · 621 likes · top 97%

Description

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

You may perform the following operation any number of times: choose any element and flip one bit in its binary representation (changing a 0 to 1 or vice versa).

Return the minimum number of operations needed to make the bitwise XOR of all elements equal to k.

Leading zero bits may also be flipped, e.g., (101)2 can become (1101)2.

Example 1:

Input: nums = [2,1,3,4], k = 1
Output: 2
Explanation: We can do the following operations:
- Choose element 2 which is 3 == (011)2, we flip the first bit and we obtain (010)2 == 2. nums becomes [2,1,2,4].
- Choose element 0 which is 2 == (010)2, we flip the third bit and we obtain (110)2 = 6. nums becomes [6,1,2,4].
The XOR of elements of the final array is (6 XOR 1 XOR 2 XOR 4) == 1 == k.
It can be shown that we cannot make the XOR equal to k in less than 2 operations.

Example 2:

Input: nums = [2,0,2,0], k = 0
Output: 0
Explanation: The XOR of elements of the array is (2 XOR 0 XOR 2 XOR 0) == 0 == k. So no operation is needed.

Code

1
2
3