#2683

Neighboring Bitwise XOR

Medium
ArrayBit ManipulationBit ManipulationArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of generating all possible arrays, we can leverage the properties of XOR. The XOR of all elements in the derived array must be 0 for a valid original array to exist.

⚙️

Algorithm

2 steps
  1. 1Step 1: Calculate the XOR of all elements in the derived array.
  2. 2Step 2: If the result is 0, return true; otherwise, return false.
solution.py2 lines
1def is_valid_original(derived):
2    return reduce(lambda x, y: x ^ y, derived) == 0

Complexity note: The complexity is O(n) because we only need to traverse the derived array once to compute the XOR.

  • 1The XOR of all derived elements must equal 0 for a valid original array.
  • 2Each element in the original array contributes to two derived elements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.