Decode XORed Permutation - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
encoded = [3,1]
›
Output:
[1,2,3]
💡 Note:
If perm = [1,2,3], then encoded[0] = 1⊕2 = 3 and encoded[1] = 2⊕3 = 1, giving us [3,1]
Example 2 — Different Permutation
$
Input:
encoded = [6,5,4,6]
›
Output:
[2,4,1,5,3]
💡 Note:
The permutation [2,4,1,5,3] produces: [2⊕4, 4⊕1, 1⊕5, 5⊕3] = [6,5,4,6]
Example 3 — Minimum Size
$
Input:
encoded = [2,1]
›
Output:
[1,3,2]
💡 Note:
Smallest valid case: [1,3,2] gives [1⊕3, 3⊕2] = [2,1]
Constraints
- 3 ≤ n ≤ 105
- n is odd
- encoded.length == n - 1
- perm is a permutation of [1, 2, ..., n]
Visualization
Tap to expand
Understanding the Visualization
1
Input
Encoded array where encoded[i] = perm[i] ⊕ perm[i+1]
2
Process
Use XOR properties to reverse the encoding process
3
Output
Original permutation of numbers 1 to n
Key Takeaway
🎯 Key Insight: XOR is reversible - if A⊕B=C, then A=C⊕B, allowing us to decode the permutation step by step
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code