LeetCode 1734: Decode XORed Permutation Solution

Master LeetCode problem 1734 (Decode XORed Permutation), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1734. Decode XORed Permutation

Problem Explanation

Explanation

To decode the XORed permutation, we need to find the original permutation array perm given the encoded array. Since perm is a permutation of the first n positive integers, we know that perm can be derived by XORing all elements from 1 to n. By using the properties of XOR operation, we can find the first element of perm and then calculate the rest of the elements iteratively.

  1. Find the XOR of all elements from 1 to n.
  2. Find the XOR of all elements in the encoded array.
  3. XOR the result of step 1 with the result of step 2 to get the first element of perm.
  4. Iterate through the encoded array to find the rest of the elements of perm.

Time Complexity: O(n) where n is the length of the encoded array.

Space Complexity: O(n) for storing the decoded permutation.

Solution Code

class Solution {
    public int[] decode(int[] encoded) {
        int n = encoded.length + 1;
        int[] perm = new int[n];
        
        int totalXOR = 0;
        for (int i = 1; i <= n; i++) {
            totalXOR ^= i;
        }
        
        int encodedXOR = 0;
        for (int i = 1; i < n - 1; i += 2) {
            encodedXOR ^= encoded[i];
        }
        
        perm[0] = totalXOR ^ encodedXOR;
        
        for (int i = 1; i < n; i++) {
            perm[i] = perm[i - 1] ^ encoded[i - 1];
        }
        
        return perm;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1734 (Decode XORed Permutation)?

This page provides optimized solutions for LeetCode problem 1734 (Decode XORed Permutation) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1734 (Decode XORed Permutation)?

The time complexity for LeetCode 1734 (Decode XORed Permutation) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1734 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1734 in Java, C++, or Python.

Back to LeetCode Solutions