Leetcode 2433: Find The Original Array of Prefix Xor

grid47
grid47
Exploring patterns and algorithms
Mar 8, 2024 5 min read

You are given an integer array pref of size n. Your task is to find and return an array arr of size n that satisfies the following condition: each element pref[i] equals the XOR of all elements from arr[0] to arr[i]. In other words, pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i] where ^ denotes the bitwise XOR operation. It is guaranteed that there is a unique solution.
Problem
Approach
Steps
Complexity
Input: You are given a single array `pref` of integers.
Example: pref = [3, 1, 2, 6]
Constraints:
• 1 <= pref.length <= 10^5
• 0 <= pref[i] <= 10^6
Output: Return an array `arr` that satisfies the condition: `pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]`.
Example: Output: [3, 2, 0, 6]
Constraints:
• The answer will always be unique.
Goal: We need to find an array `arr` such that the cumulative XOR of its elements matches the corresponding values in `pref`.
Steps:
• 1. Initialize an empty array `arr` of the same size as `pref`.
• 2. Set `arr[0]` equal to `pref[0]` since the first element is directly equal.
• 3. For each subsequent index `i`, calculate `arr[i]` as `pref[i] ^ pref[i-1]`. This is because `pref[i]` represents the cumulative XOR of `arr[0]` to `arr[i]`, and `pref[i-1]` represents the cumulative XOR of `arr[0]` to `arr[i-1]`, so XORing them will give the value of `arr[i]`.
• 4. Return the array `arr`.
Goal: Consider the following constraints while designing the solution.
Steps:
• The array `pref` has at least one element.
• The XOR operation is associative and commutative.
Assumptions:
• The input array `pref` is valid and contains at least one element.
• Each element of `pref` is non-negative and less than or equal to 10^6.
Input: pref = [3, 1, 2, 6]
Explanation: To solve this, we find `arr` such that each `pref[i]` is the cumulative XOR of `arr[0]` to `arr[i]`. From `pref`, we can derive `arr` as follows: `arr[0] = 3`, `arr[1] = 3 ^ 1 = 2`, `arr[2] = 2 ^ 2 = 0`, `arr[3] = 0 ^ 6 = 6`. Thus, the result is `[3, 2, 0, 6]`.

Input: pref = [10]
Explanation: In this case, the array `arr` will be equal to `pref[0]` because there is only one element. Thus, the result is `[10]`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus