#2433

Find The Original Array of Prefix Xor

Medium
ArrayBit ManipulationBit ManipulationArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach leverages the properties of XOR to directly compute each element of the original array using the prefix XOR values, leading to a linear time solution.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty array `arr` of the same length as `pref`.
  2. 2Step 2: Set `arr[0]` to `pref[0]` since it's the first element.
  3. 3Step 3: For each index `i` from 1 to n-1, compute `arr[i]` using the formula: `arr[i] = pref[i] ^ pref[i - 1]`.
  4. 4Step 4: Return the constructed array `arr`.
solution.py7 lines
1def findOriginalArray(pref):
2    n = len(pref)
3    arr = [0] * n
4    arr[0] = pref[0]
5    for i in range(1, n):
6        arr[i] = pref[i] ^ pref[i - 1]
7    return arr

Complexity note: The time complexity is O(n) because we are iterating through the array once, performing constant time operations for each element. The space complexity is O(n) due to the additional array used to store the result.

  • 1XOR is reversible, meaning if you know the result of an XOR operation and one of the operands, you can find the other operand.
  • 2The first element of the original array is always the same as the first element of the prefix array.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.