Decode XORed Array (LeetCode 1720): Solution and Explanation
Recover arr from its neighbour XORs encoded and its first value first.
Intuition
Each encoded value ties two neighbours together: encoded[i] = arr[i] ^ arr[i + 1]. If you know one end of that link, the other end is fixed.
XOR undoes itself. XOR both sides with arr[i] and the arr[i] on the right cancels, because x ^ x = 0, leaving arr[i + 1] = arr[i] ^ encoded[i].
arr[0] is given, so the first link reveals arr[1], the next link reveals arr[2], and so on down the chain in a single pass.
Approach: Left to right XOR unrolling
- Start the answer with
arr = [first]. - For each
xinencoded, appendarr[-1] ^ x. - Return
arr.
Step-by-step example
encoded = [1,2,3], first = 1
- arr[0] = 1.
- arr[1] = 1 ^ 1 = 0.
- arr[2] = 0 ^ 2 = 2.
- arr[3] = 2 ^ 3 = 1.
- Return [1,0,2,1].
Code: Python, Java, C++
1class Solution:
2 def decode(self, encoded: List[int], first: int) -> List[int]:
3 arr = [first]
4 for x in encoded:
5 arr.append(arr[-1] ^ x)
6 return arr1class Solution {
2 public int[] decode(int[] encoded, int first) {
3 int[] arr = new int[encoded.length + 1];
4 arr[0] = first;
5 for (int i = 0; i < encoded.length; i++) {
6 arr[i + 1] = arr[i] ^ encoded[i];
7 }
8 return arr;
9 }
10}1class Solution {
2public:
3 vector<int> decode(vector<int>& encoded, int first) {
4 vector<int> arr(encoded.size() + 1);
5 arr[0] = first;
6 for (int i = 0; i < (int)encoded.size(); i++) {
7 arr[i + 1] = arr[i] ^ encoded[i];
8 }
9 return arr;
10 }
11};Time and space complexity
O(n)
One XOR per element of encoded.
O(n)
Only the output array is allocated; no extra working memory is needed.
Other approaches
Prefix XOR of encoded (time O(n), space O(n))
arr[i] = first ^ encoded[0] ^ ... ^ encoded[i - 1], because the inner terms cancel in pairs. Keeping a running XOR gives the same pass written another way.
Decode in place (time O(n), space O(n))
Overwrite encoded while walking it, keeping the previous decoded value in a variable, then prepend first. Saves no asymptotic space since the output still has n values.
Common mistakes
- Returning only n - 1 values. The answer has one more element than encoded because first must be included.
- XORing with encoded[i + 1] instead of encoded[i]. The link between arr[i] and arr[i + 1] is encoded[i].
- Trying subtraction or addition to invert the encoding. Only XOR cancels cleanly.
Frequently asked questions
Why is the answer unique?
Once arr[0] is fixed, each step arr[i + 1] = arr[i] ^ encoded[i] has exactly one result, so every later value is forced.
What if first were not given?
Then any starting value would work, since XORing every element of a valid arr with the same constant leaves all neighbour XORs unchanged. The problem gives first to pin down one answer.
Can the values overflow?
No. XOR never produces a bit above the highest bit of its inputs, and all inputs are at most 10^5, so every value fits in 17 bits.