Problem Description
Given an integer array pref where for every index i, pref[i] is defined as the XOR of all elements from arr[0] to arr[i] (i.e. pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]), recover and return the original array arr.
Key Insights
- The first element of arr is the same as pref[0].
- For i > 0, arr[i] can be obtained by XOR-ing pref[i] with pref[i-1] because XOR is its own inverse.
- The problem guarantees that the solution is unique.
- The XOR operation has properties that help in inverting prefix computations.
Space and Time Complexity
Time Complexity: O(n) - We traverse the array once. Space Complexity: O(n) - We use an extra array to store the result.
Solution
The key idea is to use the property of XOR where a ^ b ^ b = a. Given that pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i], we can deduce that for i > 0, arr[i] = pref[i-1] ^ pref[i]. We initiate arr[0] with pref[0] and then for each index i from 1 to n-1, we compute arr[i] using the XOR of pref[i-1] and pref[i]. This method is efficient and runs in linear time while using linear space.