Find The Original Array of Prefix Xor (LeetCode 2433): Solution and Explanation

Medium
Array
Bit Manipulation

Given the running XOR pref of an unknown array, rebuild the array itself.

Intuition

pref[i] is the XOR of arr[0] through arr[i], and pref[i - 1] is the XOR of arr[0] through arr[i - 1]. The two cover the same elements except arr[i].

XOR cancels anything that appears twice, because x ^ x = 0. So pref[i - 1] ^ pref[i] wipes out arr[0..i - 1] and leaves exactly arr[i].

This is the XOR version of recovering an array from its prefix sums by subtracting neighbours, except XOR is its own inverse so there is no separate subtraction.

Approach: XOR of adjacent prefixes

  1. Set arr[0] = pref[0].
  2. For i from 1 to n - 1, set arr[i] = pref[i - 1] ^ pref[i].
  3. Return arr.

Step-by-step example

pref = [5,2,0,3,1]
  1. arr[0] = pref[0] = 5.
  2. arr[1] = 5 ^ 2 = 7.
  3. arr[2] = 2 ^ 0 = 2.
  4. arr[3] = 0 ^ 3 = 3.
  5. arr[4] = 3 ^ 1 = 2, so return [5,7,2,3,2].

Code: Python, Java, C++

1class Solution:
2    def findArray(self, pref: List[int]) -> List[int]:
3        arr = [pref[0]]
4        for i in range(1, len(pref)):
5            arr.append(pref[i - 1] ^ pref[i])
6        return arr
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One XOR per position.

Space

O(n)

Only the output array is allocated. Writing the answer back into pref from right to left would need no extra array at all.

Other approaches

In place, right to left (time O(n), space O(1) extra)

Walk i from n - 1 down to 1 and set pref[i] ^= pref[i - 1]. Going right to left keeps pref[i - 1] unchanged until it is used.

Running XOR (time O(n), space O(n))

Keep acc = XOR of the arr values found so far and set arr[i] = acc ^ pref[i], then fold arr[i] into acc. Same result, since acc always equals pref[i - 1].

Common mistakes

  • Updating pref in place from left to right. pref[i - 1] would already be overwritten when computing arr[i].
  • Forgetting arr[0]. It has no earlier prefix and equals pref[0] directly.
  • Using subtraction as for prefix sums. XOR prefixes are undone with XOR, not minus.

Frequently asked questions

Why is the answer unique?

arr[0] must equal pref[0], and every later arr[i] is forced to be pref[i - 1] ^ pref[i]. There is no choice at any step.

Can the values grow beyond the input range?

No. XOR never sets a bit above the highest bit of its inputs, so every answer value is below 2^20 when pref values are at most 10^6.

How does this relate to Decode XORed Array?

It is the reverse picture. There, each given value is the XOR of two neighbours of arr; here, the XOR of two neighbours of pref is the value of arr.