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 INPUT encoded array (n-1 elements) 3 index 0 1 index 1 XOR Encoding: encoded[i] = perm[i] XOR perm[i+1] p[0] XOR p[1] XOR p[2] = 3 = 1 encoded = [3, 1], n = 3 ALGORITHM STEPS 1 Compute totalXOR XOR of 1 to n: 1^2^3 = 0 total = 0 2 Compute oddXOR XOR encoded at odd indices odd = encoded[1] = 1 3 Find perm[0] perm[0] = totalXOR XOR oddXOR perm[0] = 0^1 = 1 4 Reconstruct perm perm[i+1] = perm[i] XOR encoded[i] p[1] = p[0]^e[0] = 1^3 = 2 p[2] = p[1]^e[1] = 2^1 = 3 oddXOR = p[1]^p[2]^...^p[n-1] (pairs of adjacent elements) FINAL RESULT Original Permutation 1 perm[0] 2 perm[1] 3 perm[2] Verification: perm[0] XOR perm[1] = 1 XOR 2 = 3 [OK] perm[1] XOR perm[2] = 2 XOR 3 = 1 [OK] OUTPUT: [1, 2, 3] Time: O(n) | Space: O(n) Key Insight: Since n is always ODD, XORing encoded values at odd indices gives us perm[1] XOR perm[2] XOR ... XOR perm[n-1]. Combined with totalXOR (1 XOR 2 XOR ... XOR n), we can isolate perm[0] = totalXOR XOR oddXOR. This works because each pair in encoded at odd positions contributes all elements except perm[0]. TutorialsPoint - Decode XORed Permutation | Optimal Solution
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