Find The Original Array of Prefix Xor Problem
#2433
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2433.
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.
Example 1:
Input: pref = [5,2,0,3,1]
Output: [5,7,2,3,2]
Explanation: From the array [5,7,2,3,2] we have the following:
- pref[0] = 5.
- pref[1] = 5 ^ 7 = 2.
- pref[2] = 5 ^ 7 ^ 2 = 0.
- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3.
- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1.
Example 2:
Input: pref = [13]
Output: [13]
Explanation: We have pref[0] = arr[0] = 13.
Constraints:
1 <= pref.length <= 10^50 <= pref[i] <= 10^6
Solution
Approach: Bit Manipulation
We have pref[i] = arr[0] ^ ... ^ arr[i] and pref[i-1] = arr[0] ^ ... ^ arr[i-1]. XOR-ing the two cancels everything but arr[i], so arr[i] = pref[i] ^ pref[i-1], with arr[0] = pref[0].
Complexity: The time complexity is O(n) and the space complexity is O(1) besides the answer, where n is the length of pref.
class Solution:
def findArray(self, pref: List[int]) -> List[int]:
return [pref[0]] + [pref[i - 1] ^ pref[i] for i in range(1, len(pref))]