Decode XORed Permutation — LeetCode 1734 Python Solution

MediumBit ManipulationArray
Problem
#1734
Reading time
2 min

The problem

There is an integer array perm that is a permutation of the first n positive integers, where n is always odd. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1].

Example

Input
encoded = [3,1]
Output
[1,2,3]
Explanation
If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]

Python solution

Python
class Solution:
    def decode(self, encoded: List[int]) -> List[int]:
        n = len(encoded) + 1
        a = b = 0
        for i in range(0, n - 1, 2):
            a ^= encoded[i]
        for i in range(1, n + 1):
            b ^= i
        perm = [0] * n
        perm[-1] = a ^ b
        for i in range(n - 2, -1, -1):
            perm[i] = encoded[i] ^ perm[i + 1]
        return perm

Complexity

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

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1734. Decode XORed Permutation 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 1734. Decode XORed Permutation?
LeetCode 1734. Decode XORed Permutation is rated Medium on LeetCode.
What is the time complexity of LeetCode 1734. Decode XORed Permutation?
The Python solution on this page runs in O(n), where n is the length of the array perm.
What is the space complexity of LeetCode 1734. Decode XORed Permutation?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1734. Decode XORed Permutation cover?
LeetCode 1734. Decode XORed Permutation 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