There is an integer array perm that is a permutation of the first n positive integers, where n is always odd.
It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1].
Given the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique.
class Solution {
public int[] decode(int[] encoded) {
int n = encoded.length + 1;
int[] res = new int[n];
/*
key is to calculate the first element
we know (a1 ^ a2), (a2 ^ a3), (a3 ^ a4), (a4 ^ a5)
we can calculate (a1 ^ a3), (a1 ^ a4), (a1 ^ a5)
we can also calculate (a1 ^ a2 ^ a3 ^ a4 ^ a5)
then we can calcualte a1 by
a1 = (a1 ^ a2) ^ (a1 ^ a3) ^ (a1 ^ a4) ^ (a1 ^ a5) ^ (a1 ^ a2 ^ a3 ^ a4 ^ a5)
*/
int a1 = 0;
int encode = 0;
for (int i = 0; i < encoded.length; i ++) {
encode = encode ^ encoded[i];
a1 = a1 ^ encode;
}
for (int i = 1; i <= n; i ++) {
a1 = a1 ^ i;
}
res[0] = a1;
for (int i = 1; i < n; i ++) {
res[i] = res[i - 1] ^ encoded[i - 1];
}
return res;
}
}