Loading
Leetcode / 2433. Find The Original Array of Prefix Xor

Pick a programming language:

Here is the source code for the solution to this problem.

class Solution {
    public int[] findArray(int[] pref) {
        int[] arr = new int[pref.length];
        arr[0] = pref[0];

        for (int i = 1; i < pref.length; i++) {
            // the previous element already computes the XOR up to i - 1.
            // If you have pref[i] = arr[0] XOR arr[1] ... XOR arr[i]
            // then you can do pref[i] = (pref[i - 1]) XOR arr[i]
            // The XOR operation of a = b XOR c can also be written as c = b XOR a:
            arr[i] = pref[i - 1] ^ pref[i];
        }

        return arr;
    }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: