Leetcode 1720: Decode XORed Array

grid47
grid47
Exploring patterns and algorithms
May 19, 2024 5 min read

You are given an encoded array of length n - 1, where each element encoded[i] represents the XOR of two consecutive elements in the original array arr, i.e., encoded[i] = arr[i] XOR arr[i + 1]. You are also given the first element of the original array arr[0]. Your task is to decode the array and return the original array arr.
Problem
Approach
Steps
Complexity
Input: You are given an array `encoded` of length `n - 1` and an integer `first` which is the first element of the original array `arr`.
Example: Input: encoded = [5, 8, 10], first = 2
Constraints:
• 2 <= n <= 10^4
• encoded.length == n - 1
• 0 <= encoded[i] <= 10^5
• 0 <= first <= 10^5
Output: Return the decoded array `arr`.
Example: Output: [2, 7, 15, 5]
Constraints:
• The decoded array will always exist and be unique.
Goal: The goal is to reverse the encoding process and reconstruct the original array `arr` using the given `encoded` array and the first element of `arr`.
Steps:
• 1. Start by initializing the array `arr` with the first element `first`.
• 2. Iterate through the `encoded` array, and for each value, compute the next element in the original array using XOR: `arr[i + 1] = arr[i] XOR encoded[i]`.
• 3. Continue this process until the entire original array is reconstructed.
Goal: The input constraints are designed to ensure that the solution can be computed efficiently for large arrays.
Steps:
• The `encoded` array is always of length `n - 1`.
• The value of `first` is non-negative and fits within the constraints.
Assumptions:
• It is guaranteed that a unique solution exists for every input.
Input: Input: encoded = [1, 2, 3], first = 1
Explanation: The original array is `[1, 0, 2, 1]`. Using the formula `arr[i+1] = arr[i] XOR encoded[i]`, we can reconstruct the array as follows: `arr[0] = 1`, `arr[1] = arr[0] XOR encoded[0] = 1 XOR 1 = 0`, `arr[2] = arr[1] XOR encoded[1] = 0 XOR 2 = 2`, and `arr[3] = arr[2] XOR encoded[2] = 2 XOR 3 = 1`.

Input: Input: encoded = [6, 2, 7, 3], first = 4
Explanation: The original array is `[4, 2, 0, 7, 4]`. Reconstructing each element: `arr[0] = 4`, `arr[1] = arr[0] XOR encoded[0] = 4 XOR 6 = 2`, `arr[2] = arr[1] XOR encoded[1] = 2 XOR 2 = 0`, `arr[3] = arr[2] XOR encoded[2] = 0 XOR 7 = 7`, and `arr[4] = arr[3] XOR encoded[3] = 7 XOR 3 = 4`.

Link to LeetCode Lab


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