LeetCode 2433. Find The Original Array of Prefix Xor Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2433. Find The Original Array of Prefix Xor

Description

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 <= 105
  • 0 <= pref[i] <= 106

Solutions

Solution 1: Bit Manipulation

According to the problem statement, we have equation one:

pref[i]=arr[0] \oplus arr[1] \oplus … \oplus arr[i]

So, we also have equation two:

pref[i-1]=arr[0] \oplus arr[1] \oplus … \oplus arr[i-1]

We perform a bitwise XOR operation on equations one and two, and get:

pref[i] \oplus pref[i-1]=arr[i]

That is, each item in the answer array is obtained by performing a bitwise XOR operation on the adjacent two items in the prefix XOR array.

The time complexity is O(n), where n is the length of the prefix XOR array. Ignoring the space consumption of the answer, the space complexity is O(1).

PythonJavaC++GoTypeScriptRustC
class Solution: def findArray(self, pref: List[int]) -> List[int]: return [a ^ b for a, b in pairwise([0] + pref)](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !