Skip to content

2997. Minimum Number of Operations to Make Array XOR Equal to K 👍

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
class Solution {
 public:
  int minOperations(vector<int>& nums, unsigned k) {
    const unsigned xors = accumulate(nums.begin(), nums.end(), 0, bit_xor<>());
    return popcount(k ^ xors);
  }
};
1
2
3
4
5
6
class Solution {
  public int minOperations(int[] nums, int k) {
    final int xors = Arrays.stream(nums).reduce((a, b) -> a ^ b).getAsInt();
    return Integer.bitCount(k ^ xors);
  }
}
1
2
3
class Solution:
  def minOperations(self, nums: list[int], k: int) -> int:
    return functools.reduce(operator.xor, nums, k).bit_count()