Decode XORed Array - Problem
Decode XORed Array is a fascinating bit manipulation problem that demonstrates the reversible nature of XOR operations.

You're given a mysterious encoded array that was created by XOR-ing adjacent elements of an original array. For example, if the original array was [1,0,2,1], the encoded array would be [1,2,3] where each element represents arr[i] XOR arr[i+1].

Your mission: Given the encoded array and the first element of the original array, reconstruct the complete original array.

Key insight: Since XOR is its own inverse (a XOR b XOR b = a), you can use the encoded values to step through and rebuild the original array one element at a time.

Input & Output

example_1.py โ€” Basic Case
$ Input: encoded = [1,2,3], first = 1
โ€บ Output: [1,0,2,1]
๐Ÿ’ก Note: Starting with first=1, we calculate: arr[1] = 1โŠ•1 = 0, arr[2] = 2โŠ•0 = 2, arr[3] = 3โŠ•2 = 1. The XOR verification works: [1โŠ•0, 0โŠ•2, 2โŠ•1] = [1,2,3]
example_2.py โ€” Single Element
$ Input: encoded = [6], first = 1
โ€บ Output: [1,7]
๐Ÿ’ก Note: With only one encoded value, we get arr[1] = 6โŠ•1 = 7. Verification: 1โŠ•7 = 6 โœ“
example_3.py โ€” Zeros and Large Numbers
$ Input: encoded = [0,2,1], first = 4
โ€บ Output: [4,4,6,7]
๐Ÿ’ก Note: Starting with 4: arr[1] = 0โŠ•4 = 4, arr[2] = 2โŠ•4 = 6, arr[3] = 1โŠ•6 = 7. Shows that XOR with 0 preserves the value.

Constraints

  • 1 โ‰ค encoded.length โ‰ค 103
  • 0 โ‰ค encoded[i] โ‰ค 105
  • 0 โ‰ค first โ‰ค 105
  • The answer is guaranteed to exist and be unique

Visualization

Tap to expand
XOR Decoding Chain ReactionInput:encoded = [1, 2, 3], first = 11arr[0] = first0arr[1] = 1โŠ•12arr[2] = 2โŠ•01arr[3] = 3โŠ•2โŠ•1โŠ•2โŠ•3Encoded Array123Algorithm Steps1. result[0] = first2. For each encoded[i]:result[i+1] = encoded[i] โŠ• result[i]
Understanding the Visualization
1
Start with the known first element
This is our anchor point - we know arr[0] = first
2
Use XOR's self-inverse property
Since encoded[0] = arr[0] โŠ• arr[1], we get arr[1] = encoded[0] โŠ• arr[0]
3
Continue the chain reaction
Each decoded element helps decode the next: arr[i+1] = encoded[i] โŠ• arr[i]
4
Complete reconstruction
Process all encoded values to rebuild the entire original array
Key Takeaway
๐ŸŽฏ Key Insight: XOR is its own inverse operation, making it perfect for encoding/decoding schemes. Once you know one element and the XOR relationships, you can reconstruct the entire sequence in linear time!
Asked in
Google 25 Amazon 18 Microsoft 12 Meta 8
28.6K Views
Medium Frequency
~8 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