Neighboring Bitwise XOR - Problem
Reverse Engineering Binary Array from XOR Operations

Imagine you have a secret binary array (containing only 0's and 1's) that has been transformed using a specific XOR pattern. Your task is to determine if a given derived array could have been created from some valid binary array using this transformation.

The transformation rule is: For each position i in the original array:
  • If i is the last position, then derived[i] = original[i] ⊕ original[0] (XOR with first element)
  • Otherwise, derived[i] = original[i] ⊕ original[i + 1] (XOR with next element)

Goal: Given a derived array, return true if there exists a valid binary array that could have produced it, false otherwise.

Example: If derived = [1, 1, 0], we need to check if there's a binary array [a, b, c] such that [a⊕b, b⊕c, c⊕a] = [1, 1, 0]

Input & Output

example_1.py — Valid Array Exists
$ Input: [1, 1, 0]
Output: true
💡 Note: We can find original = [1, 0, 1] which produces derived = [1⊕0, 0⊕1, 1⊕1] = [1, 1, 0]. XOR sum: 1⊕1⊕0 = 0 ✓
example_2.py — No Valid Array
$ Input: [1, 1, 1]
Output: false
💡 Note: XOR sum: 1⊕1⊕1 = 1 ≠ 0, so no valid original array exists. Each element would need to appear twice but sum to 1.
example_3.py — Single Element
$ Input: [0]
Output: true
💡 Note: For n=1, derived[0] = original[0] ⊕ original[0] = 0. Since derived[0] = 0, original = [0] works. XOR sum: 0 = 0 ✓

Visualization

Tap to expand
XOR Property: Why Sum Must Be Zeroabca⊕bb⊕cc⊕aXOR Sum Analysis:(a⊕b) ⊕ (b⊕c) ⊕ (c⊕a) = a⊕b⊕b⊕c⊕c⊕a= (a⊕a) ⊕ (b⊕b) ⊕ (c⊕c) = 0 ⊕ 0 ⊕ 0 = 0✓ Each element appears exactly twice → XOR sum = 0
Understanding the Visualization
1
Original Array Setup
We have an unknown binary array [a, b, c, ...]
2
XOR Transformation
Each element XORs with its neighbor (last wraps to first)
3
Mathematical Analysis
When we XOR all derived values, each original appears exactly twice
4
Key Insight
Since x⊕x = 0, the total XOR sum must be 0 for valid arrays
Key Takeaway
🎯 Key Insight: The circular XOR pattern ensures each original element appears exactly twice in the sum, making the total XOR equal to 0 for any valid array.

Time & Space Complexity

Time Complexity
⏱️
O(n)

Single pass through the array to compute XOR sum, plus optional O(n) to construct solution

n
2n
Linear Growth
Space Complexity
O(1)

Only using a few variables for XOR computation

n
2n
Linear Space

Constraints

  • 1 ≤ derived.length ≤ 105
  • derived[i] is either 0 or 1
  • All values are binary (0 or 1)
Asked in
ByteDance 15 Microsoft 12 Amazon 8 Google 6
23.5K Views
Medium Frequency
~12 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen