Decode XORed Permutation Problem
Description
LeetCode Problem 1734.
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.
Example 1:
Input: encoded = [3,1]
Output: [1,2,3]
Explanation: If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]
Example 2:
Input: encoded = [6,5,4,6]
Output: [2,4,1,5,3]
Constraints:
3 <= n < 10^5nis odd.encoded.length == n - 1
Solution
Approach: Bit Manipulation
perm is a permutation of 1..n with n odd, so the XOR of all its elements is a = 1 XOR 2 XOR ... XOR n.
Because encoded[i] = perm[i] XOR perm[i + 1], XOR-ing the values at even positions encoded[0], encoded[2], ..., encoded[n - 3] gives b = perm[0] XOR perm[1] XOR ... XOR perm[n - 2], which is every element except the last one. Hence perm[n - 1] = a XOR b.
Once the last element is known, walk encoded backwards: perm[i] = perm[i + 1] XOR encoded[i].
Complexity: O(n) time and O(1) extra space, where n is the length of perm.
class Solution:
def decode(self, encoded: List[int]) -> List[int]:
n = len(encoded) + 1
a = b = 0
for i in range(0, n - 1, 2):
a ^= encoded[i]
for i in range(1, n + 1):
b ^= i
perm = [0] * n
perm[-1] = a ^ b
for i in range(n - 2, -1, -1):
perm[i] = encoded[i] ^ perm[i + 1]
return perm