Leetcode 1734: Decode XORed Permutation

grid47
grid47
Exploring patterns and algorithms
May 17, 2024 6 min read

You are given an array encoded of length n - 1, which represents the XOR of consecutive elements of a permutation of the first n integers. Your task is to decode the encoded array and return the original permutation perm of size n.
Problem
Approach
Steps
Complexity
Input: The input consists of a single integer array `encoded` of length `n - 1`, where `encoded[i] = perm[i] XOR perm[i + 1]`. The permutation `perm` is a permutation of integers from `1` to `n` and `n` is odd.
Example: Input: encoded = [4, 3, 7]
Constraints:
• 3 <= n < 10^5
• n is odd
• encoded.length == n - 1
Output: Return the decoded permutation array `perm` of size `n`.
Example: Output: [2, 4, 1, 5, 3]
Constraints:
• The output is a list of integers representing the decoded permutation of the integers from 1 to n.
Goal: The goal is to decode the encoded array and reconstruct the original permutation by finding a way to use XOR operations efficiently.
Steps:
• 1. Compute the XOR of all integers from 1 to n.
• 2. XOR every second element of the `encoded` array with the computed XOR to obtain the first element of the permutation.
• 3. Use the XOR relationship between consecutive elements of the permutation to find the entire permutation array.
• 4. Return the reconstructed permutation array.
Goal: The given array `encoded` satisfies the following constraints:
Steps:
• The length of `encoded` is `n - 1` where n is an odd integer.
• The elements in `encoded` are derived using XOR operations from consecutive elements of the permutation array.
Assumptions:
• The encoded array always provides a valid and unique solution for the permutation.
• The permutation consists of the integers from 1 to n, and each integer appears exactly once.
Input: Input: encoded = [4, 3, 7]
Explanation: The XOR of all integers from 1 to 5 is 7. XORing every second element of `encoded` with 7 gives the first element of the permutation, which is 2. Then we can use the XOR of consecutive elements to find the rest of the permutation.

Input: Input: encoded = [3, 1]
Explanation: If perm = [1, 2, 3], then `encoded = [1 XOR 2, 2 XOR 3] = [3, 1]`. Therefore, the decoded permutation is [1, 2, 3].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus