Find The Original Array of Prefix Xor
MediumUpdated: Aug 2, 2025
Practice on:
Problem
You are given an integer array pref of size n. Find and return the arrayarr of sizen that satisfies :
pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].
Note that ^ denotes the bitwise-xor operation.
It can be proven that the answer is unique.
Examples
Example 1
Input: pref = [5,2,0,3,1]
Output: [5,7,2,3,2]
Explanation: From the array [5,7,2,3,2] we have the following:
- pref[0] = 5.
- pref[1] = 5 ^ 7 = 2.
- pref[2] = 5 ^ 7 ^ 2 = 0.
- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3.
- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1.
Example 2
Input: pref = [13]
Output: [13]
Explanation: We have pref[0] = arr[0] = 13.
Constraints
1 <= pref.length <= 10^50 <= pref[i] <= 10^6
Solution
Method 1 – Prefix XOR Property
Intuition
Given the prefix XOR array, we can recover the original array by using the property: arr[0] = pref[0], and for i > 0, arr[i] = pref[i] ^ pref[i-1]. This is because pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i], so arr[i] = pref[i] ^ pref[i-1] (since XOR is its own inverse).
Approach
- Initialize
arr[0] = pref[0]. - For each
ifrom 1 to n-1, setarr[i] = pref[i] ^ pref[i-1]. - Return the array.
Code
C++
class Solution {
public:
vector<int> findArray(vector<int>& pref) {
int n = pref.size();
vector<int> ans(n);
ans[0] = pref[0];
for (int i = 1; i < n; ++i) {
ans[i] = pref[i] ^ pref[i-1];
}
return ans;
}
};
Go
func findArray(pref []int) []int {
n := len(pref)
ans := make([]int, n)
ans[0] = pref[0]
for i := 1; i < n; i++ {
ans[i] = pref[i] ^ pref[i-1]
}
return ans
}
Java
class Solution {
public int[] findArray(int[] pref) {
int n = pref.length;
int[] ans = new int[n];
ans[0] = pref[0];
for (int i = 1; i < n; ++i) {
ans[i] = pref[i] ^ pref[i-1];
}
return ans;
}
}
Kotlin
class Solution {
fun findArray(pref: IntArray): IntArray {
val n = pref.size
val ans = IntArray(n)
ans[0] = pref[0]
for (i in 1 until n) {
ans[i] = pref[i] xor pref[i-1]
}
return ans
}
}
Python
class Solution:
def findArray(self, pref: list[int]) -> list[int]:
n = len(pref)
ans = [0] * n
ans[0] = pref[0]
for i in range(1, n):
ans[i] = pref[i] ^ pref[i-1]
return ans
Rust
impl Solution {
pub fn find_array(pref: Vec<i32>) -> Vec<i32> {
let n = pref.len();
let mut ans = vec![0; n];
ans[0] = pref[0];
for i in 1..n {
ans[i] = pref[i] ^ pref[i-1];
}
ans
}
}
TypeScript
class Solution {
findArray(pref: number[]): number[] {
const n = pref.length;
const ans = new Array(n);
ans[0] = pref[0];
for (let i = 1; i < n; ++i) {
ans[i] = pref[i] ^ pref[i-1];
}
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(n)— One pass through the array. - 🧺 Space complexity:
O(n)— For the output array.