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
Your mission: Given the
Key insight: Since XOR is its own inverse (
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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code