Find The Original Array of Prefix Xor

Given an integer array pref of size n, find and return the array arr of size n such that pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i], where ^ is bitwise XOR. The answer is unique.

30:00

Find The Original Array of Prefix Xor
medium
Free written solution
Topics
Companies

Given an integer array pref of size n, find and return the array arr of size n such that pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i], where ^ is bitwise XOR. The answer is unique.

Example 1:
Input: {"pref":[5,2,0,3,1]}
Output: [5,7,2,3,2]
Constraints:
  • 1≤pref.length≤1051 \leq \text{pref.length} \leq 10^5

  • 0≤pref[i]≤1060 \leq \text{pref}[i] \leq 10^6

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

Run code to see results.

Input
arr ={"pref":[5,2,0,3,1]}

pref[i] is the XOR of arr[0..i]. Two neighbouring prefixes share everything except arr[i], so XORing them cancels the shared part.

Two prefixes differ by one element

0/5 recovered

pref[0]
5
pref[1]
2
pref[2]
0
pref[3]
3
pref[4]
1
?
arr[0]
?
arr[1]
?
arr[2]
?
arr[3]
?
arr[4]

pref[i - 1] ^ pref[i] = arr[i]

pref[i-1]
^ pref[i]
= arr[i]
Variables
VariableValue
n5
DepthFunction Call
Stack empty
0/10