Find The Original Array of Prefix Xor - Complete Solution Guide
Find The Original Array of Prefix Xor is LeetCode problem 2433, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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
Detailed Explanation
The problem asks us to reconstruct the original array `arr` given its prefix XOR array `pref`. The prefix XOR array `pref` is defined such that `pref[i]` is the XOR of all elements from `arr[0]` to `arr[i]`. The goal is to find `arr` from `pref`. For example, if `pref = [5, 2, 0, 3, 1]`, then `arr` should be `[5, 7, 2, 3, 2]` because `5 = 5`, `5 ^ 7 = 2`, `5 ^ 7 ^ 2 = 0`, `5 ^ 7 ^ 2 ^ 3 = 3`, and `5 ^ 7 ^ 2 ^ 3 ^ 2 = 1`. The input is a non-empty array `pref` of integers, and the output is the original array `arr`.
Solution Approach
The solution exploits the properties of the XOR operation. Specifically, if `a ^ b = c`, then `a = c ^ b` and `b = c ^ a`. We can iterate through the `pref` array from the second element onwards (index 1). For each element at index `i`, we replace `pref[i]` with `pref[i] ^ pref[i-1]`. This results in the original array `arr` being stored in the `pref` array itself.
Step-by-Step Algorithm
- Step 1: Initialize the first element of the `arr` array as the first element of the `pref` array. In essence, `arr[0] = pref[0]`.
- Step 2: Iterate through the `pref` array from index 1 to the end of the array.
- Step 3: For each index `i`, calculate `pref[i] = pref[i] ^ pref[i-1]`. This step overwrites the `pref` array with the correct values for the `arr` array.
- Step 4: Return the modified `pref` array, which now holds the original `arr` array.
Key Insights
- Insight 1: The key insight is understanding the relationship between `pref[i]` and `arr[i]`. We know `pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]`. Therefore, `arr[i]` can be obtained by `pref[i] ^ pref[i-1]`.
- Insight 2: The first element of `arr` is simply the first element of `pref` since `pref[0] = arr[0]`.
- Insight 3: We can perform the XOR operation in-place, modifying the `pref` array directly to store the resulting `arr` values, minimizing space usage.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Array, Bit Manipulation.
Companies
Asked at: IBM, Morgan Stanley, Nvidia.