MediumNo. 1734

Decode XORed Permutation — LeetCode 1734 Python Solution

Topics
Bit Manipulation, Array
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

PythonSolution
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

Time
O(n)where n is the length of the array perm
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0136Single NumberEasy
0137Single Number IIMedium
0260Single Number IIIMedium
0287Find the Duplicate NumberMedium
0318Maximum Product of Word LengthsMedium
0393UTF-8 ValidationMedium

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.

Free to download. Check it runs on your machine, then pick a plan.