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 <= 1050 <= pref[i] <= 106This approach involves iterating through the prefix XOR array and using the properties of XOR to deduce the original array. Starting from the first element, which is the same as in the original array, subsequent elements can be found using the formula:
arr[i] = pref[i] ^ pref[i-1]
since pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i] and pref[i-1] = arr[0] ^ arr[1] ^ ... ^ arr[i-1].
This C program first stores the first element in the pref array into the arr array since they are the same. For subsequent elements, it uses the XOR operation with the previous prefix value to deduce the original numbers. The use of a simple loop makes the implementation straightforward.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(n)
This approach calculates each element of the original array directly by using the property of XOR that makes it its own inverse. By understanding that the difference between consecutive prefix values gives the desired element, this method is implemented in a direct computational manner.
This C solution reflects the direct calculation of the original array using XOR directly on the prefix elements. Using principles similar to other approaches, this code shows how directly the computation can be managed given the XOR properties.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(n)
| Approach | Complexity |
|---|---|
| Iterative Approach | Time Complexity: O(n) |
| Prefix XOR Direct Computation | Time Complexity: O(n) |
LeetCode 2433. Find The Original Array of Prefix Xor - Interview Prep Ep 131 • Fisher Coder • 1,424 views views
Watch 9 more video solutions →Practice Find The Original Array of Prefix Xor with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor