#1734

Decode XORed Permutation

Medium
ArrayBit ManipulationBit ManipulationArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the properties of XOR and the fact that n is odd. By computing the XOR of all numbers from 1 to n and using the encoded array, we can derive the original permutation efficiently.

⚙️

Algorithm

4 steps
  1. 1Step 1: Compute the XOR of all numbers from 1 to n (let's call this totalXor).
  2. 2Step 2: Compute the XOR of all elements in the encoded array (let's call this encodedXor).
  3. 3Step 3: The first element of perm can be found as first = totalXor XOR encodedXor.
  4. 4Step 4: Initialize perm[0] with first and use the encoded array to fill the rest of perm using perm[i] = perm[i-1] XOR encoded[i-1].
solution.py13 lines
1def decode_optimal(encoded):
2    n = len(encoded) + 1
3    totalXor = 0
4    for i in range(1, n + 1):
5        totalXor ^= i
6    encodedXor = 0
7    for num in encoded:
8        encodedXor ^= num
9    first = totalXor ^ encodedXor
10    perm = [first]
11    for i in range(len(encoded)):
12        perm.append(perm[-1] ^ encoded[i])
13    return perm

Complexity note: This complexity arises because we iterate through the encoded array and the range from 1 to n, leading to linear growth in time with respect to n.

  • 1XOR is a powerful tool for solving problems involving pairs of numbers, especially when the order doesn't matter.
  • 2The fact that n is odd guarantees that there will be a unique solution, which simplifies our approach.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.