Problem Description
Given an encoded array, where each encoded[i] represents the XOR of consecutive elements (arr[i] XOR arr[i+1]) of a hidden non-negative integer array arr, and the first element of arr is provided as first, reconstruct the original array arr.
Key Insights
- The XOR operation is reversible: if a XOR b = c, then a XOR c = b.
- Since encoded[i] = arr[i] XOR arr[i+1], we can obtain arr[i+1] by computing arr[i] XOR encoded[i].
- Start with the given first element and iterate through encoded to build the entire original array.
Space and Time Complexity
Time Complexity: O(n), as we iterate over the encoded array once. Space Complexity: O(n), for storing the decoded array.
Solution
We initialize the resulting array arr with the provided first element. Then, for every element in the encoded array, we compute the next element as the XOR of the current element in arr and the corresponding encoded value. This uses the property of XOR, which allows us to recover one operand if the other operand and the result are known.