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 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: 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
Minimum Operations to Make Array XOR Equal to K INPUT nums array: 2 1 3 4 Binary representation: 010 001 011 100 Target k = 1 k = 001 Current XOR: 2^1^3^4 = 4 (100) ALGORITHM STEPS 1 Compute XOR of array xorSum = 2^1^3^4 = 4 2 XOR with target k diff = xorSum ^ k = 4^1 = 5 3 Count set bits in diff diff = 5 = 101 in binary 4 Return bit count popcount(101) = 2 diff = 101 Bit 0: 1 (flip) Bit 2: 1 (flip) FINAL RESULT XOR difference analysis: Current XOR: 100 (4) Target k: 001 (1) Difference: 101 (5) Bits that need flipping: 1 bit 2 0 bit 1 1 bit 0 Minimum Operations 2 OK - Solution verified Key Insight: Flipping a bit in ANY array element flips the same bit position in the total XOR. So we need to flip exactly the bits that differ between current XOR and target k. The answer = number of set bits in (XOR of all nums) XOR k = popcount(4 ^ 1) = popcount(5) = 2 TutorialsPoint - Minimum Number of Operations to Make Array XOR Equal to K | Optimal Solution
Asked in
Google 25 Microsoft 20 Amazon 15
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen