Find The Original Array of Prefix Xor (LeetCode 2433): Solution and Explanation
Given the running XOR pref of an unknown array, rebuild the array itself.
Intuition
pref[i] is the XOR of arr[0] through arr[i], and pref[i - 1] is the XOR of arr[0] through arr[i - 1]. The two cover the same elements except arr[i].
XOR cancels anything that appears twice, because x ^ x = 0. So pref[i - 1] ^ pref[i] wipes out arr[0..i - 1] and leaves exactly arr[i].
This is the XOR version of recovering an array from its prefix sums by subtracting neighbours, except XOR is its own inverse so there is no separate subtraction.
Approach: XOR of adjacent prefixes
- Set
arr[0] = pref[0]. - For
ifrom 1 to n - 1, setarr[i] = pref[i - 1] ^ pref[i]. - Return
arr.
Step-by-step example
pref = [5,2,0,3,1]
- arr[0] = pref[0] = 5.
- arr[1] = 5 ^ 2 = 7.
- arr[2] = 2 ^ 0 = 2.
- arr[3] = 0 ^ 3 = 3.
- arr[4] = 3 ^ 1 = 2, so return [5,7,2,3,2].
Code: Python, Java, C++
1class Solution:
2 def findArray(self, pref: List[int]) -> List[int]:
3 arr = [pref[0]]
4 for i in range(1, len(pref)):
5 arr.append(pref[i - 1] ^ pref[i])
6 return arr1class Solution {
2 public int[] findArray(int[] pref) {
3 int n = pref.length;
4 int[] arr = new int[n];
5 arr[0] = pref[0];
6 for (int i = 1; i < n; i++) {
7 arr[i] = pref[i - 1] ^ pref[i];
8 }
9 return arr;
10 }
11}1class Solution {
2public:
3 vector<int> findArray(vector<int>& pref) {
4 int n = pref.size();
5 vector<int> arr(n);
6 arr[0] = pref[0];
7 for (int i = 1; i < n; i++) {
8 arr[i] = pref[i - 1] ^ pref[i];
9 }
10 return arr;
11 }
12};Time and space complexity
O(n)
One XOR per position.
O(n)
Only the output array is allocated. Writing the answer back into pref from right to left would need no extra array at all.
Other approaches
In place, right to left (time O(n), space O(1) extra)
Walk i from n - 1 down to 1 and set pref[i] ^= pref[i - 1]. Going right to left keeps pref[i - 1] unchanged until it is used.
Running XOR (time O(n), space O(n))
Keep acc = XOR of the arr values found so far and set arr[i] = acc ^ pref[i], then fold arr[i] into acc. Same result, since acc always equals pref[i - 1].
Common mistakes
- Updating pref in place from left to right. pref[i - 1] would already be overwritten when computing arr[i].
- Forgetting arr[0]. It has no earlier prefix and equals pref[0] directly.
- Using subtraction as for prefix sums. XOR prefixes are undone with XOR, not minus.
Frequently asked questions
Why is the answer unique?
arr[0] must equal pref[0], and every later arr[i] is forced to be pref[i - 1] ^ pref[i]. There is no choice at any step.
Can the values grow beyond the input range?
No. XOR never sets a bit above the highest bit of its inputs, so every answer value is below 2^20 when pref values are at most 10^6.
How does this relate to Decode XORed Array?
It is the reverse picture. There, each given value is the XOR of two neighbours of arr; here, the XOR of two neighbours of pref is the value of arr.