[Leet Code] Decode XORed Array

Matthew Boyd
2 min readFeb 12, 2021

--

Leetcode: https://leetcode.com/problems/decode-xored-array/

Problem:

There is a hidden integer array arr that consists of n non-negative integers.

It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3].

You are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0].

Return the original array arr. It can be proved that the answer exists and is unique.

Example 1:

Input: encoded = [1,2,3], first = 1
Output: [1,0,2,1]
Explanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]

Example 2:

Input: encoded = [6,2,7,3], first = 4
Output: [4,2,0,7,4]

Solution:

class Solution(object):
def decode(self, encoded, first):
"""
:type encoded: List[int]
:type first: int
:rtype: List[int]
"""
ans = [first]
for i in encoded:
ans.append(ans[-1]^i)

return ans

Explanation, first we make an answer variable that contains the value of the first integer, as you can see from the examples, it’s always the first integer in the answers. Then we continue through the encoded array one by one, and we append to the answers array, the product of ans[-1] (the last value in the answers array) XORed by the element we’re cycling through. Then we return the answers array.

--

--

Matthew Boyd
Matthew Boyd

Written by Matthew Boyd

Learning, and posting my findings!

No responses yet