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 INPUT encoded array: 1 2 3 [0] [1] [2] first value: 1 encoded[i] = arr[i] XOR arr[i+1] encoded = [1, 2, 3] first = 1 n = 4 (arr length) n-1 = 3 (encoded length) ALGORITHM STEPS 1 Initialize arr arr[0] = first = 1 2 Use XOR property A XOR B = C means A XOR C = B 3 Iterate and decode arr[i+1] = arr[i] XOR encoded[i] 4 Build result Return decoded array Computation Steps: arr[0] = 1 (given) arr[1] = 1 XOR 1 = 0 arr[2] = 0 XOR 2 = 2 arr[3] = 2 XOR 3 = 1 Time: O(n) | Space: O(n) FINAL RESULT Decoded array arr: 1 0 2 1 [0] [1] [2] [3] [1, 0, 2, 1] Verification: 1 XOR 0 = 1 [OK] 0 XOR 2 = 2 [OK] 2 XOR 1 = 3 [OK] SUCCESS Key Insight: XOR is self-inverse: if A XOR B = C, then A XOR C = B. This allows us to reverse the encoding process. Starting with arr[0] = first, we can recover each arr[i+1] = arr[i] XOR encoded[i]. TutorialsPoint - Decode XORed Array | Optimal Solution O(n)
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