Minimum Number of Operations to Make Array XOR Equal to K - Problem
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
0to1or 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: You can flip leading zero bits in the binary representation of elements. For example, for the number (101)₂ you can flip the fourth bit and obtain (1101)₂.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,1,3,4], k = 1
›
Output:
2
💡 Note:
Current XOR = 2⊕1⊕3⊕4 = 4. To get k=1, we need 4⊕1=5. Binary 5 = 101 has 2 bits set, so 2 operations needed.
Example 2 — Already Equal
$
Input:
nums = [2,0,2,0], k = 0
›
Output:
0
💡 Note:
Current XOR = 2⊕0⊕2⊕0 = 0, which equals k=0. No operations needed.
Example 3 — Single Element
$
Input:
nums = [5], k = 3
›
Output:
2
💡 Note:
Current XOR = 5. To get k=3, we need 5⊕3=6. Binary 6 = 110 has 2 bits set, so 2 operations needed.
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ nums[i] ≤ 106
- 0 ≤ k ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [2,1,3,4] with target k=1
2
Calculate XOR
Find XOR of all elements = 4
3
Compare & Count
4⊕1=5, count bits in 5 = 2 operations
Key Takeaway
🎯 Key Insight: Only the bit positions where current XOR differs from target K need to be flipped
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code