Decode XORed Array

A hidden integer array arr of n non-negative integers was encoded into encoded of length n - 1, where encoded[i] = arr[i] XOR arr[i + 1]. Given encoded and the first element first = arr[0], return the original array arr. The answer exists and is unique.

30:00

Decode XORed Array
easy
Free written solution
Topics
Companies

A hidden integer array arr of n non-negative integers was encoded into encoded of length n - 1, where encoded[i] = arr[i] XOR arr[i + 1]. Given encoded and the first element first = arr[0], return the original array arr. The answer exists and is unique.

Example 1:
Input: {"encoded":[1,2,3],"first":1}
Output: [1,0,2,1]
Constraints:
  • 2≤n≤1042 \leq n \leq 10^4

  • encoded.length=n−1\text{encoded.length} = n - 1

  • 0≤encoded[i]≤1050 \leq \text{encoded}[i] \leq 10^5

  • 0≤first≤1050 \leq \text{first} \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"encoded":[1,2,3],"first":1}

Each encoded[i] is the XOR of two neighbours, arr[i] ^ arr[i + 1]. Since x ^ x = 0, XORing a known neighbour back in reveals the other one.

Unroll the chain: each link is arr[i] ^ arr[i+1]

0/4 known

1
e[0]
2
e[1]
3
e[2]
?
arr[0]
?
arr[1]
?
arr[2]
?
arr[3]

known end XOR link = other end

arr[i]
^ e[i]
= ?
Variables
VariableValue
first1
encoded.length3
DepthFunction Call
Stack empty
0/8