Problem Description
Given an array derived of length n, where derived[i] is the XOR of two adjacent elements of a binary array original (with the rule that derived[n-1] = original[n-1] XOR original[0]), determine if there exists a valid binary array original that can generate the derived array.
Key Insights
- The original array elements are either 0 or 1.
- Constructing the original array based on an assumed starting value (either 0 or 1) leads to a cyclic dependency.
- By successively XOR’ing the starting value with the derived elements, the computed last element must equal the starting value.
- This boils down to checking whether the XOR of all derived elements is 0 (for cases when n > 1). For n == 1, ensure that derived[0] is 0.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the derived array. Space Complexity: O(1) as only a constant amount of extra space is used.
Solution
We can solve the problem by realizing that if we pick an initial value for original[0], then we can compute the rest of the original array, because:
- original[1] = original[0] XOR derived[0]
- original[2] = original[1] XOR derived[1] = original[0] XOR derived[0] XOR derived[1]
- Continue this process until original[n-1].
- Finally, because the array is circular, derived[n-1] = original[n-1] XOR original[0]. This leads to the equation: original[0] XOR (derived[0] XOR derived[1] ... XOR derived[n-1]) == original[0]
- Cancelling out original[0] from both sides, we obtain that the XOR of all derived elements must be 0.
Thus, if the XOR of all values in derived is 0, a valid binary original array exists.
The algorithm is simple:
- If n == 1, return true if derived[0] is 0, otherwise false.
- For n > 1, check if reduce(XOR) across all elements equals 0.