Find The Original Array of Prefix Xor - XOR [JS]

Description 

Solution: XOR

For each pref[i], we need to find the number where pref[i - 1] ^ ? = pref[i].
Look at individual bits of pref[i - 1] and pref[i] and construct the number we need:
If the bits are the same, we must take bit 0.
If the bits are different, we must take bit 1.

Notice that the bits we need to take are actually the same as the result of XORing them together.

  • 1 ^ 1 = 0
  • 0 ^ 0 = 0
  • 1 ^ 0 = 1
  • 0 ^ 1 = 1

Therefore, we can XOR each pref[i - 1] and pref[i] to get the answers.

Time Complexity: O(n) 229ms
Space Complexity: O(1) (not including output) 74.2MB

var findArray = function(pref) {
  let n = pref.length, res = Array(n);
  res[0] = pref[0];
  for (let i = 1; i < n; i++) {
    res[i] = pref[i - 1] ^ pref[i];
  }
  return res;
};

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]