2683. Neighboring Bitwise XOR #1162
-
Topics: A 0-indexed array Specifically, for each index
Given an array Return true if such an array exists or false otherwise.
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
To determine whether a valid binary array Key Observations:
Steps:
Algorithm:
Let's implement this solution in PHP: 2683. Neighboring Bitwise XOR <?php
/**
* @param Integer[] $derived
* @return Boolean
*/
function doesValidArrayExist($derived) {
$xorSum = 0;
// Compute the XOR of all elements in derived
foreach ($derived as $value) {
$xorSum ^= $value;
}
// If the XOR sum is 0, a valid original array exists
return $xorSum === 0;
}
// Example 1
$derived1 = [1, 1, 0];
echo doesValidArrayExist($derived1) ? 'true' : 'false'; // Output: true
// Example 2
$derived2 = [1, 1];
echo doesValidArrayExist($derived2) ? 'true' : 'false'; // Output: true
// Example 3
$derived3 = [1, 0];
echo doesValidArrayExist($derived3) ? 'true' : 'false'; // Output: false
?> Explanation:
Complexity:
This approach efficiently checks for the existence of a valid |
Beta Was this translation helpful? Give feedback.
To determine whether a valid binary array
original
exists that could form the givenderived
array, we can use the properties of XOR:Key Observations:
Each
derived[i]
is the XOR of two adjacent elements inoriginal
:i = n - 1
,derived[i] = original[n-1] ⊕ original[0]
.derived[i] = original[i] ⊕ original[i+1]
.XOR properties:
a ⊕ a = 0
(XOR of a number with itself is 0).a ⊕ 0 = a
(XOR of a number with 0 is the number itself).To construct a valid
original
, the XOR of all elements inderived
must equal 0. Why? Because for a circular XOR relationship to work (start and end wrap back to the beginning), the cumulative XOR ofderived
…