2023-10-31 Daily Challenge

Today I have done leetcode's October LeetCoding Challenge with cpp.

October LeetCoding Challenge 31

Description

Find The Original Array of Prefix Xor

You are given an integer array pref of size n. Find and return the array arr of size n that satisfies:

  • pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].

Note that ^ denotes the bitwise-xor operation.

It can be proven that the answer is unique.

 

Example 1:

Input: pref = [5,2,0,3,1]
Output: [5,7,2,3,2]
Explanation: From the array [5,7,2,3,2] we have the following:
- pref[0] = 5.
- pref[1] = 5 ^ 7 = 2.
- pref[2] = 5 ^ 7 ^ 2 = 0.
- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3.
- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1.

Example 2:

Input: pref = [13]
Output: [13]
Explanation: We have pref[0] = arr[0] = 13.

 

Constraints:

  • 1 <= pref.length <= 105
  • 0 <= pref[i] <= 106

Solution

auto speedup = [](){
  cin.tie(nullptr);
  cout.tie(nullptr);
  ios::sync_with_stdio(false);
  return 0;
}();
class Solution {
public:
  vector<int> findArray(vector<int>& pref) {
    vector<int> answer;
    answer.reserve(pref.size());
    int prev = 0;
    for(auto n : pref) {
      answer.push_back(prev ^ n);
      prev = n;
    }

    return answer;
  }
};

// Accepted
// 46/46 cases passed (67 ms)
// Your runtime beats 98.71 % of cpp submissions
// Your memory usage beats 83.5 % of cpp submissions (76.2 MB)