LeetCode 2683: Neighboring Bitwise XOR
Problem Description
Explanation
To solve this problem, we need to find a valid original array that could have formed the given derived array by computing the bitwise XOR of adjacent elements. We can observe that for each index i
, the derived value at index i
is the result of XOR operation between original values at index i
and i+1
(or 0
if i = n-1
).
We can start by iterating through the derived array and check if we can construct the original array based on the XOR property. If we encounter any inconsistency during this process, we return false
. Otherwise, we return true
.
The time complexity of this approach is O(n) where n is the length of the derived array. The space complexity is O(1) as we are not using any extra space apart from a few variables.
Solutions
class Solution {
public boolean validateBinaryArray(int[] derived) {
int n = derived.length;
for (int i = 0; i < n; i++) {
if (derived[i] != (i == n - 1 ? derived[i] ^ derived[0] : derived[i] ^ derived[i + 1])) {
return false;
}
}
return true;
}
}
Loading editor...