Neighboring Bitwise XOR — LeetCode 2683 Python Solution

MediumBit ManipulationArray
Problem
#2683
Reading time
2 min

The 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].

Example

Input
derived = [1,1,0]
Output
true
Explanation
A valid original array that gives derived is [0,1,0].

Python solution

Python
class Solution:
    def doesValidArrayExist(self, derived: List[int]) -> bool:
        return reduce(xor, derived) == 0

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2683. Neighboring Bitwise XOR is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2683. Neighboring Bitwise XOR?
LeetCode 2683. Neighboring Bitwise XOR is rated Medium on LeetCode.
What is the time complexity of LeetCode 2683. Neighboring Bitwise XOR?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 2683. Neighboring Bitwise XOR?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2683. Neighboring Bitwise XOR cover?
LeetCode 2683. Neighboring Bitwise XOR is tagged Bit Manipulation and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview