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
Decode XORed Permutation: From Encoded to OriginalOriginal Permutation:132XORXOREncoded Array:211⊕3=23⊕2=1Decoding Process:1. Calculate total XOR: 1⊕2⊕3 = 02. XOR at odd indices: encoded[1] = 13. First element: 0⊕1 = 14. Next: 1⊕2 = 35. Next: 3⊕1 = 2Decoded: [1,3,2]Success: Original permutation recovered!
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
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen