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.
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).
classSolution {
publicint[]findArray(int[] pref) {
int n = pref.length;
int[] ans =newint[n];
ans[0]= pref[0];
for (int i = 1; i < n; ++i) {
ans[i]= pref[i]^ pref[i-1];
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funfindArray(pref: IntArray): IntArray {
val n = pref.size
val ans = IntArray(n)
ans[0] = pref[0]
for (i in1 until n) {
ans[i] = pref[i] xor pref[i-1]
}
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
deffindArray(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
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnfind_array(pref: Vec<i32>) -> Vec<i32> {
let n = pref.len();
letmut ans =vec![0; n];
ans[0] = pref[0];
for i in1..n {
ans[i] = pref[i] ^ pref[i-1];
}
ans
}
}