2997. Minimum Number of Operations to Make Array XOR Equal to K #2357
Replies: 1 comment
-
|
We are given an array Approach:The problem requires transforming the array such that the XOR of all elements equals The key insight is that the XOR of all elements in the array initially computes to a value, say Let's implement this solution in PHP: 2997. Minimum Number of Operations to Make Array XOR Equal to K <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function minOperations(array $nums, int $k): int
{
$xors = array_reduce($nums, function($carry, $item) {
return $carry ^ $item;
}, 0);
return substr_count(decbin($k ^ $xors), '1');
}
// Test cases
echo minOperations([2, 1, 3, 4], 1); // Output: 2
echo "\n";
echo minOperations([2, 0, 2, 0], 0); // Output: 0
?>Explanation:
Time Complexity
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Topics:
Array,Bit Manipulation,Biweekly Contest 121You are given a 0-indexed integer array
numsand a positive integerk.You can apply the following operation on the array any number of times:
anyelement of the array andflipa bit in itsbinaryrepresentation. Flipping abitmeans changing a0to1or vice versa.Return the minimum number of operations required to make the bitwise
XORof all elements of the final array equal tok.Note that you can flip leading zero bits in the binary representation of elements. For example, for the number (101)
(1101)2you can flip the fourth bit and obtain(1101)2.Example 1:
andwe obtain (010)2 == 2. nums becomes [2,1,2,4].andwe obtain (110)2 = 6. nums becomes [6,1,2,4].Example 2:
Constraints:
1 <= nums.length <= 1050 <= nums[i] <= 1060 <= k <= 106Hint:
XORof all elements of the original array and compare it tokin their binary representation.XORof elements of the original array andkwe have to flip exactly one bit of an element innumsto make that bit equal.Beta Was this translation helpful? Give feedback.
All reactions