Decode XORed Array - Problem

There is a hidden integer array arr that consists of n non-negative integers.

It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3].

You are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0].

Return the original array arr. It can be proved that the answer exists and is unique.

Input & Output

Example 1 — Basic Case
$ Input: encoded = [1,2,3], first = 1
Output: [1,0,2,1]
💡 Note: Starting with arr[0] = 1, we decode: arr[1] = 1⊕1 = 0, arr[2] = 0⊕2 = 2, arr[3] = 2⊕3 = 1
Example 2 — Different Values
$ Input: encoded = [6,2,7,3], first = 4
Output: [4,2,0,7,4]
💡 Note: arr[0] = 4, arr[1] = 4⊕6 = 2, arr[2] = 2⊕2 = 0, arr[3] = 0⊕7 = 7, arr[4] = 7⊕3 = 4
Example 3 — Minimum Size
$ Input: encoded = [5], first = 3
Output: [3,6]
💡 Note: With only one encoded value: arr[0] = 3, arr[1] = 3⊕5 = 6

Constraints

  • 2 ≤ encoded.length ≤ 104
  • 0 ≤ encoded[i] ≤ 105
  • 0 ≤ first ≤ 105

Visualization

Tap to expand
Decode XORed Array: Reverse the Encoding ProcessOriginal Array (Hidden)1021Encoded Array (Given)1231⊕00⊕22⊕1Decoding ProcessGiven: first = 1arr[1] = 1 ⊕ 1 = 0arr[2] = 0 ⊕ 2 = 2arr[3] = 2 ⊕ 3 = 1Decoded: [1, 0, 2, 1]
Understanding the Visualization
1
Given
Encoded array [1,2,3] and first element 1
2
Decode
Use XOR properties to recover original array
3
Result
Original array [1,0,2,1]
Key Takeaway
🎯 Key Insight: XOR is reversible - use arr[i+1] = arr[i] ⊕ encoded[i] to decode step by step
Asked in
Amazon 15 Microsoft 12
28.5K Views
Medium Frequency
~10 min Avg. Time
890 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