Problem
A 0-indexed array derived
with length n
is derived by computing the bitwise XOR (⊕) of adjacent values in a binary array original
of length n
.
Specifically, for each index i
in the range [0, n - 1]
:
- If
i = n - 1
, thenderived[i] = original[i] ⊕ original[0]
. - Otherwise,
derived[i] = original[i] ⊕ original[i + 1]
.
Given an array derived
, your task is to determine whether there exists a valid binary array original
that could have formed derived
.
Return true if such an array exists or false otherwise.
- A binary array is an array containing only 0’s and 1’s
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
n == derived.length
1 <= n <= 10^5
- The values in
derived
are either 0 ’s or 1 ’s
Solution
Video explanation
Here is the video explaining below methods in detail. Please check it out:
Method 1 - Xor of whole of derived should be 0
Lets take original
array be A[0], A[1], ... A[n-1]
.
Then the derived array will be:
|
|
Now, we know that:
|
|
So, if we perform XOR between the elements of derived, they should cancel out:
So, if xoring the derived values results in 0, we can derive this array from original array.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
- We iterate through thederived
array once. - 🧺 Space complexity:
O(1)
, We use a constant amount of extra space (variable to store XOR value).
Method 2 - Sum should be even
If the xor values of derived is 0, and derived
is a binary array, then:
- Each XOR operation will essentially contribute either
0
or1
to thederived
array. - For the XOR of all
derived
elements to be zero, they must pair off and cancel each other out (sincex ⊕ x = 0
).
When dealing with binary elements:
- An even count of
1
s ensures they can cancel each other out in pairs (every1
in the XOR sequence finds another1
to pair with and cancel out). - Therefore, for the
derived
array to be valid (derived from a validoriginal
array), the sum of1
s (i.e., the sum of its elements) must be even.
Code
|
|
|
|