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

Beautiful Towers II - Monotonic Increasing Stack [JS]

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

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

Maximum Score After Applying Operations on a Tree - DFS [JS]

Divide Nodes Into the Maximum Number of Groups - Union Find & BFS [JS]