Leetcode 1720. Decode XORed Array
A decoder has provided you with an integer array encoded
of length n
and an integer first
. The encoded
array is generated by encoding an original array arr
, in such a way that:
encoded[i] = arr[i] XOR arr[i+1]
for i
in the range 0 <= i < n
.You are required to decode the original array arr
. To achieve this, an integer first
is given as the initial value arr[0]
.
Return the original array arr
.
Input:
encoded = [1,2,3], first = 1
Output:
[1,0,2,1]
Q: What is the length of the encoded
array?
A: The length of the encoded
array is n
.
Q: What will be the length of the original array arr
?
A: The length of the original array arr
would be n + 1
.
Q: Are the values in the array positive numbers? A: The values in the arrays can be zero or positive integers.
arr
with a size of n + 1
.arr[0]
to the given first
value.encoded[i] = arr[i] XOR arr[i + 1]
, and knowing that arr[i + 1] = encoded[i] XOR arr[i]
, we can calculate each value of arr
iteratively.0
to n-1
, calculating arr[i + 1]
using the formula arr[i + 1] = encoded[i] XOR arr[i]
.#include <vector>
#include <iostream>
std::vector<int> decode(std::vector<int>& encoded, int first) {
int n = encoded.size();
std::vector<int> arr(n + 1);
arr[0] = first;
for (int i = 0; i < n; ++i) {
arr[i + 1] = encoded[i] ^ arr[i];
}
return arr;
}
// Example to run the code
int main() {
std::vector<int> encoded = {1, 2, 3};
int first = 1;
std::vector<int> decoded_array = decode(encoded, first);
for (int num : decoded_array) {
std::cout << num << " ";
}
return 0;
}
The solution runs in linear time:
O(n)
, where n
is the length of the encoded array.O(n + 1)
, due to the storage required for the resulting array arr
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?