Neighboring Bitwise XOR

medium array bit manipulation xor parity

Problem

A binary array original of length n produces derived by XOR-ing adjacent values cyclically: derived[i] = original[i] ⊕ original[i+1] for i < n−1, and derived[n−1] = original[n−1] ⊕ original[0]. Given derived, decide whether any valid binary original could have formed it. Return true if one exists, otherwise false.

Inputderived = [1, 1, 0]
Outputtrue
original = [0, 1, 0] works: 0⊕1=1, 1⊕0=1, 0⊕0=0. The XOR of all derived values is 1⊕1⊕0 = 0, so a valid original exists.

def doesValidArrayExist(derived):
    # Each original[i] is used in exactly two derived terms,
    # so XOR-ing all derived values cancels every original[i].
    x = 0
    for v in derived:
        x ^= v               # fold the next derived bit into the running XOR
    # A valid original exists iff that total parity is 0.
    return x == 0
function doesValidArrayExist(derived) {
  // Each original[i] appears in two derived terms, so the XOR
  // of all derived values cancels every original[i] pairwise.
  let x = 0;
  for (const v of derived) {
    x ^= v;                // fold the next derived bit into the running XOR
  }
  // A valid original exists iff that total parity is 0.
  return x === 0;
}
boolean doesValidArrayExist(int[] derived) {
    // Each original[i] appears in two derived terms, so the XOR
    // of all derived values cancels every original[i] pairwise.
    int x = 0;
    for (int v : derived) {
        x ^= v;            // fold the next derived bit into the running XOR
    }
    // A valid original exists iff that total parity is 0.
    return x == 0;
}
bool doesValidArrayExist(vector<int>& derived) {
    // Each original[i] appears in two derived terms, so the XOR
    // of all derived values cancels every original[i] pairwise.
    int x = 0;
    for (int v : derived) {
        x ^= v;            // fold the next derived bit into the running XOR
    }
    // A valid original exists iff that total parity is 0.
    return x == 0;
}
Time: O(n) Space: O(1)