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 arrayperm. It is guaranteed that the answer exists and is unique.
The encoded array is formed by XORing consecutive elements of a permutation of the first n positive integers. Since n is odd, we can use the properties of XOR to recover the original permutation. The key is that XOR-ing all numbers from 1 to n and all encoded values in a certain pattern allows us to deduce the first element, and then reconstruct the rest.
classSolution {
public: vector<int> decode(vector<int>& encoded) {
int n = encoded.size() +1;
int total =0;
for (int i =1; i <= n; ++i) total ^= i;
int odd =0;
for (int i =1; i < n -1; i +=2) odd ^= encoded[i];
vector<int> ans(n);
ans[0] = total ^ odd;
for (int i =0; i < n -1; ++i) {
ans[i +1] = ans[i] ^ encoded[i];
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
funcdecode(encoded []int) []int {
n:= len(encoded) +1total:=0fori:=1; i<=n; i++ {
total ^= i }
odd:=0fori:=1; i < n-1; i+=2 {
odd ^= encoded[i]
}
ans:= make([]int, n)
ans[0] = total ^ oddfori:=0; i < n-1; i++ {
ans[i+1] = ans[i] ^ encoded[i]
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
publicint[]decode(int[] encoded) {
int n = encoded.length+ 1;
int total = 0;
for (int i = 1; i <= n; i++) total ^= i;
int odd = 0;
for (int i = 1; i < n - 1; i += 2) odd ^= encoded[i];
int[] ans =newint[n];
ans[0]= total ^ odd;
for (int i = 0; i < n - 1; i++) {
ans[i + 1]= ans[i]^ encoded[i];
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
fundecode(encoded: IntArray): IntArray {
val n = encoded.size + 1var total = 0for (i in1..n) total = total xor i
var odd = 0for (i in1 until n - 1 step 2) odd = odd xor encoded[i]
val ans = IntArray(n)
ans[0] = total xor odd
for (i in0 until n - 1) {
ans[i + 1] = ans[i] xor encoded[i]
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defdecode(self, encoded: list[int]) -> list[int]:
n: int = len(encoded) +1 total: int =0for i in range(1, n +1):
total ^= i
odd: int =0for i in range(1, n -1, 2):
odd ^= encoded[i]
ans: list[int] = [0] * n
ans[0] = total ^ odd
for i in range(n -1):
ans[i +1] = ans[i] ^ encoded[i]
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
impl Solution {
pubfndecode(encoded: Vec<i32>) -> Vec<i32> {
let n = encoded.len() +1;
letmut total =0;
for i in1..=n asi32 {
total ^= i;
}
letmut odd =0;
for i in (1..n -1).step_by(2) {
odd ^= encoded[i];
}
letmut ans =vec![0; n];
ans[0] = total ^ odd;
for i in0..n -1 {
ans[i +1] = ans[i] ^ encoded[i];
}
ans
}
}