Decode XORed Permutation LeetCode solution in Java

1
class Solution {
2
public int[] decode(int[] encoded) {
3
int n = encoded.length + 1, all = 0;
4
for (int i = 1; i <= n; ++i) { // a^b^c^d^e^f^g^h^i
5
all ^= i;
6
}
7
int x = 0;
8
for (int v : encoded) { // a^b b^c c^d d^e e^f f^g g^h h^i = a^i
9
x ^= v;
10
}
11
int mid = all ^ x; // a^b^c^d^e^f^g^h^i ^ a^i = b^c^d^e^f^g^h
12
for (int i = 1, j = encoded.length - 2; i < j; i += 2, j -= 2) {
13
// (b^c^d^e^f^g^h) ^ (b^c ^ g^h ^ d^e ^ e^f) = e
14
mid ^= encoded[i] ^ encoded[j];
15
}
16
int[] ans = new int[n];
17
ans[n / 2] = mid;
18
// a b c d e f g h i
19
// a^b b^c c^d d^e e^f f^g g^h h^i
20
for (int i = n / 2 + 1; i < n; ++i) {
21
ans[i] = encoded[i - 1] ^ ans[i - 1];
22
}
23
for (int i = n / 2 - 1; i >= 0; --i) {
24
ans[i] = encoded[i] ^ ans[i + 1];
25
}
26
return ans;
27
}
28
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0