Find The Original Array of Prefix Xor - Problem
Find The Original Array of Prefix XOR
You're given an integer array
The relationship between the arrays is defined as:
Where
Example: If original array is
•
•
•
•
It can be proven that the answer is unique.
You're given an integer array
pref of size n that represents the prefix XOR of some unknown original array. Your task is to reverse-engineer and find the original array arr.The relationship between the arrays is defined as:
pref[i] = arr[0] ⊕ arr[1] ⊕ ... ⊕ arr[i]Where
⊕ denotes the bitwise XOR operation. This means each element in pref is the XOR of all elements in the original array from index 0 up to index i.Example: If original array is
[5, 2, 0, 3], then prefix XOR array would be [5, 7, 7, 4] because:•
pref[0] = 5•
pref[1] = 5 ⊕ 2 = 7•
pref[2] = 5 ⊕ 2 ⊕ 0 = 7•
pref[3] = 5 ⊕ 2 ⊕ 0 ⊕ 3 = 4It can be proven that the answer is unique.
Input & Output
example_1.py — Basic Case
$
Input:
pref = [5, 2, 0, 3, 1]
›
Output:
[5, 7, 2, 3, 2]
💡 Note:
Starting with pref[0] = 5, we get arr[0] = 5. Then arr[1] = pref[1] ⊕ pref[0] = 2 ⊕ 5 = 7. Continuing: arr[2] = 0 ⊕ 2 = 2, arr[3] = 3 ⊕ 0 = 3, arr[4] = 1 ⊕ 3 = 2.
example_2.py — Single Element
$
Input:
pref = [13]
›
Output:
[13]
💡 Note:
With only one element, the original array is identical to the prefix array since arr[0] = pref[0].
example_3.py — Zeros and Large Numbers
$
Input:
pref = [0, 1000000, 0]
›
Output:
[0, 1000000, 1000000]
💡 Note:
arr[0] = 0, arr[1] = 1000000 ⊕ 0 = 1000000, arr[2] = 0 ⊕ 1000000 = 1000000. Note how XOR with 0 doesn't change the value.
Constraints
- 1 ≤ pref.length ≤ 105
- 0 ≤ pref[i] ≤ 106
- The answer is guaranteed to be unique
Visualization
Tap to expand
Understanding the Visualization
1
Understanding the Lock
Each pref[i] is like a locked box containing the XOR of all elements from 0 to i
2
Finding the Key
The key insight: pref[i] ⊕ pref[i-1] = arr[i] because XOR cancels out common elements
3
Unlocking Step by Step
Start with arr[0] = pref[0], then unlock each subsequent element using adjacent pref values
4
Complete Reconstruction
In just one pass, we've reconstructed the entire original array!
Key Takeaway
🎯 Key Insight: XOR's self-inverse property (A ⊕ A = 0) allows us to isolate individual array elements by canceling out common prefixes, turning an O(n²) problem into an elegant O(n) solution!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code