Ctrl K

Bit Flips to a Target XOR

Medium
You are given an array of non-negative integers values and an integer target. In one step you may pick any element and flip a single bit of its binary form, turning a 0 into a 1 or a 1 into a 0. Leading zeros can be flipped too, so a number may grow. Return the fewest steps needed for the XOR of all elements to equal target.
Example 1
values=[5, 9, 2], target=7 → 2

Right now 5 XOR 9 XOR 2 = 14, which is 1110 in binary, while 7 is 0111. They differ in two bits, and each one can be fixed with a single flip in any of the numbers.

Example 2
values=[6, 6], target=0 → 0

6 XOR 6 = 0 already, so nothing needs to change.

Example 3
values=[0], target=10 → 2

10 = 1010 has two set bits; turning both on in the zero takes two flips.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 0 ≤ values[i] ≤ 10⁶
  • 0 ≤ target ≤ 10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvery Topping Combo MediumAll Distinct Card Hands MediumThe Odd One Among Triples MediumTwo Values Without a Pair MediumSpot the Extra Copy Medium
loading Python…
Input
values=[5, 9, 2], target=7
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 90 tests on the server, hidden ones included.