Recover an Array From Its Prefix XOR Values

Quick Overview

Given the running XOR of an unknown integer array, rebuild the original array element by element. The problem tests the self-inverse property of XOR, a short uniqueness argument, and a linear-time pass that avoids the classic in-place overwrite bug.

Recover an Array From Its Prefix XOR Values

Company: IBM

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

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. ### Function Signature ```python def find_array(pref: list[int]) -> list[int]: ``` ### Constraints - `1 <= len(pref) <= 10^5` - `0 <= pref[i] <= 10^6` ### Examples ```text Input: pref = [5,2,0,3,1] Output: [5,7,2,3,2] ``` From `arr = [5, 7, 2, 3, 2]` we get `pref[0] = 5`, `pref[1] = 5 ^ 7 = 2`, `pref[2] = 5 ^ 7 ^ 2 = 0`, `pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3` and `pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1`, which matches the input. ```text Input: pref = [13] Output: [13] ``` Since there is only one element, `arr[0] = pref[0] = 13`. ```text Input: pref = [6,6,6,0] Output: [6,0,0,6] ``` The prefix XOR stays at 6 for two steps, so the next two elements must be 0. The last prefix drops to 0, which needs `arr[3] = 6` to cancel the running value.

Overview: Given the running XOR of an unknown integer array, rebuild the original array element by element. The problem tests the self-inverse property of XOR, a short uniqueness argument, and a linear-time pass that avoids the classic in-place overwrite bug.

IBM logo
IBM
Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

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.

Function Signature

def find_array(pref: list[int]) -> list[int]:

Constraints

  • 1 <= len(pref) <= 10^5
  • 0 <= pref[i] <= 10^6

Examples

Input: pref = [5,2,0,3,1]
Output: [5,7,2,3,2]

From arr = [5, 7, 2, 3, 2] we get pref[0] = 5, pref[1] = 5 ^ 7 = 2, pref[2] = 5 ^ 7 ^ 2 = 0, pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3 and pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1, which matches the input.

Input: pref = [13]
Output: [13]

Since there is only one element, arr[0] = pref[0] = 13.

Input: pref = [6,6,6,0]
Output: [6,0,0,6]

The prefix XOR stays at 6 for two steps, so the next two elements must be 0. The last prefix drops to 0, which needs arr[3] = 6 to cancel the running value.