Find The Original Array of Prefix Xor - Problem

You are given an integer array pref of size n. Find and return the array arr of size n that satisfies:

pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]

Note that ^ denotes the bitwise-xor operation.

It can be proven that the answer is unique.

Input & Output

Example 1 — Basic Case
$ Input: pref = [5,2,0,3,1]
Output: [5,7,2,3,2]
💡 Note: arr[0]=5, arr[1]=pref[1]^pref[0]=2^5=7, arr[2]=pref[2]^pref[1]=0^2=2, arr[3]=pref[3]^pref[2]=3^0=3, arr[4]=pref[4]^pref[3]=1^3=2
Example 2 — Single Element
$ Input: pref = [13]
Output: [13]
💡 Note: Single element case: arr[0] = pref[0] = 13
Example 3 — With Zeros
$ Input: pref = [0,0,0]
Output: [0,0,0]
💡 Note: arr[0]=0, arr[1]=0^0=0, arr[2]=0^0=0. All elements are zero.

Constraints

  • 1 ≤ pref.length ≤ 105
  • 0 ≤ pref[i] ≤ 106

Visualization

Tap to expand
Find The Original Array of Prefix XOR INPUT pref[] array 5 i=0 2 i=1 0 i=2 3 i=3 1 i=4 Definition: pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i] XOR Property: A ^ A = 0, A ^ 0 = A n = 5 elements ALGORITHM STEPS 1 Initialize arr[0] arr[0] = pref[0] = 5 2 Derive Formula arr[i] = pref[i] ^ pref[i-1] 3 Apply for i=1 to n-1 Loop through array 4 Return Result O(n) time, O(1) space Calculations: i=0: arr[0] = 5 i=1: 2^5 = 7 i=2: 0^2 = 2 i=3: 3^0 = 3 i=4: 1^3 = 2 FINAL RESULT arr[] - Original Array 5 i=0 7 i=1 2 i=2 3 i=3 2 i=4 Output: [5, 7, 2, 3, 2] Verification: 5 = 5 -- OK 5^7 = 2 -- OK 5^7^2 = 0 -- OK 5^7^2^3 = 3 -- OK Complexity: Time: O(n), Space: O(1) Key Insight: Since pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i] and pref[i-1] = arr[0] ^ arr[1] ^ ... ^ arr[i-1], XORing both sides: pref[i] ^ pref[i-1] = arr[i] (all previous elements cancel out via A ^ A = 0) TutorialsPoint - Find The Original Array of Prefix XOR | Optimal Solution
Asked in
Google 25 Amazon 20 Microsoft 15
28.0K Views
Medium Frequency
~12 min Avg. Time
892 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