Decode XORed Array — LeetCode 1720 Python Solution

EasyBit ManipulationArray
Problem
#1720
Reading time
2 min

The 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].

Example

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]

Python solution

Python
class Solution:
    def decode(self, encoded: List[int], first: int) -> List[int]:
        ans = [first]
        for x in encoded:
            ans.append(ans[-1] ^ x)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the array auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1720. Decode XORed Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1720. Decode XORed Array?
LeetCode 1720. Decode XORed Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 1720. Decode XORed Array?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1720. Decode XORed Array?
The Python solution on this page uses O(n), where n is the length of the array auxiliary space.
What topics does LeetCode 1720. Decode XORed Array cover?
LeetCode 1720. Decode XORed Array is tagged Bit Manipulation and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview