#1720
Decode XORed Array
EasyArrayBit ManipulationBit ManipulationArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages the properties of XOR to directly compute each element of the original array using the encoded values. This method is efficient and straightforward.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an array 'arr' of size n.
- 2Step 2: Set arr[0] to 'first'.
- 3Step 3: Iterate through the encoded array and compute arr[i+1] as arr[i] XOR encoded[i].
solution.py9 lines
1# Full working Python code
2
3def decode(encoded, first):
4 n = len(encoded) + 1
5 arr = [0] * n
6 arr[0] = first
7 for i in range(n - 1):
8 arr[i + 1] = arr[i] ^ encoded[i]
9 return arrℹ
Complexity note: The time complexity is O(n) because we iterate through the encoded array once, and the space complexity is O(n) due to the storage of the original array.
- 1XOR operation is reversible and can be used to derive original values from encoded values.
- 2The first element is crucial as it sets the base for deriving the rest of the array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.