Neighboring Bitwise XOR - Problem

A 0-indexed array derived with length n is derived by computing the bitwise XOR (⊕) of adjacent values in a binary array original of length n.

Specifically, for each index i in the range [0, n - 1]:

  • If i = n - 1, then derived[i] = original[i] ⊕ original[0].
  • Otherwise, derived[i] = original[i] ⊕ original[i + 1].

Given an array derived, your task is to determine whether there exists a valid binary array original that could have formed derived.

Return true if such an array exists or false otherwise.

A binary array is an array containing only 0's and 1's

Input & Output

Example 1 — Valid Case
$ Input: derived = [1,1,0]
Output: true
💡 Note: Original array [0,1,0] produces derived [1,1,0]: 0⊕1=1, 1⊕0=1, 0⊕0=0
Example 2 — Invalid Case
$ Input: derived = [1,0,0]
Output: false
💡 Note: No binary array can produce [1,0,0]. XOR sum = 1⊕0⊕0 = 1 ≠ 0
Example 3 — All Zeros
$ Input: derived = [0,0,0,0]
Output: true
💡 Note: Original [0,0,0,0] works: all XOR operations yield 0

Constraints

  • 1 ≤ derived.length ≤ 105
  • derived[i] is either 0 or 1

Visualization

Tap to expand
Neighboring Bitwise XOR INPUT derived[] array: 1 i=0 1 i=1 0 i=2 XOR Relationships: o[0] o[1] o[2] d[0]=1 d[1]=1 d[2]=0 derived = [1,1,0] ALGORITHM STEPS 1 XOR Property XOR all derived elements 2 Expand Formula Each original appears 2x 3 Simplify x XOR x = 0, must be 0 4 Check Result If XOR=0, return true Calculation: 1 XOR 1 XOR 0 = (1 XOR 1) XOR 0 = 0 XOR 0 = 0 (Valid!) FINAL RESULT Valid original[] exists: 0 i=0 1 i=1 0 i=2 Verification: 0 XOR 1 = 1 [OK] d[0] 1 XOR 0 = 1 [OK] d[1] 0 XOR 0 = 0 [OK] d[2] Output: true Key Insight: When we XOR all elements in derived[], each original[i] appears exactly twice (once with neighbor on each side). Since x XOR x = 0, the total XOR must equal 0 for a valid original array to exist. Time: O(n) | Space: O(1) - Just XOR all elements and check if result is 0! TutorialsPoint - Neighboring Bitwise XOR | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
13.1K Views
Medium Frequency
~15 min Avg. Time
450 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