Approach 1: Optimal

class Solution:
    def minOperations(self, nums: List[int], k: int) -> int:
        xor_all = 0
        for num in nums:
            xor_all ^= num
        
        return bin(xor_all ^ k).count('1')

Complexity

Time:
Space:

Notes

XOR is commutative and associative so order doesn’t matter. If we read the problem description a bit closely, the true goal is to turn the XOR(all elements) into . And we just need to count the number of operations. So, we just need to compare this XOR(all elements) against and see which bits are not matching and that’s going to be the result.

Other Languages