Skip to content

2683. Neighboring Bitwise XOR 👍

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
9
class Solution {
 public:
  bool doesValidArrayExist(vector<int>& derived) {
    //      original = [O[0], O[1], ..., O[n - 1]]
    //       derived = [O[0]^O[1], O[1]^O[2], ..., O[n - 1]^O[0]]
    // XOR(derivedd) = 0
    return accumulate(derived.begin(), derived.end(), 0, bit_xor<>()) == 0;
  }
};
1
2
3
4
5
6
7
8
class Solution {
  public boolean doesValidArrayExist(int[] derived) {
    //      original = [O[0], O[1], ..., O[n - 1]]
    //       derived = [O[0]^O[1], O[1]^O[2], ..., O[n - 1]^O[0]]
    // XOR(derivedd) = 0
    return Arrays.stream(derived).reduce((a, b) -> a ^ b).getAsInt() == 0;
  }
}
1
2
3
class Solution:
  def doesValidArrayExist(self, derived: list[int]) -> bool:
    return functools.reduce(operator.xor, derived) == 0