1734. Decode XORed Permutation
LeetCode 1734. Decode XORed Permutation
Description
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:
Example 2:
Constraints:
3 <= n < 10^5
n
is odd.encoded.length == n - 1
Tags
Bit Manipulation
Solution
This problem is similar to but a little bit harder than LeetCode 1720. Decode XORed Array. The difference is that we do not know the first element of the target array perm
. However, we can obtain this value by computing perm[:] ^ perm[1:]
based on the knowledge that XOR is reversible. Given that "the array perm
that is a permutation of the first n
positive integers", we can formulate that perm[:] = 1 ^ 2 ^ ... ^ n
. Shown in the figure above, which illustrated the relationship between encoded
and perm
, we know that perm[1:] = encoded[1] ^ encoded[3] ... ^ encoded[n-1]
. Thus, we are able to obtain perm[0]
, and get the following permutation via perm[i] = perm[i-1] ^ encoded[i-1]
.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?