Decode XORed Array (LeetCode 1720): Solution and Explanation

Easy
Array
Bit Manipulation

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

  1. Start the answer with arr = [first].
  2. For each x in encoded, append arr[-1] ^ x.
  3. Return arr.

Step-by-step example

encoded = [1,2,3], first = 1
  1. arr[0] = 1.
  2. arr[1] = 1 ^ 1 = 0.
  3. arr[2] = 0 ^ 2 = 2.
  4. arr[3] = 2 ^ 3 = 1.
  5. 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 arr
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One XOR per element of encoded.

Space

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.