[LeetCode] Decode XORed Permutation

1734. Decode XORed Permutation

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<int> decode(vector<int>& encoded) {
int n = encoded.size() + 1, x = 0;
vector<int> res(n);
for(int i = 1; i < n - 1; i+=2) {
x ^= encoded[i];
}
for(int i = 1; i <= n; i++)
x ^= i;
res[0] = x;
for(int i = 0; i < n - 1; i++) {
res[i + 1] = res[i] ^ encoded[i];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/27/PS/LeetCode/decode-xored-permutation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.