1545. Three-Way XOR Cuts

Medium3.5 points estimatedPrefix SumBit ManipulationHash Table

A cargo belt carries crates tagged with integer codes listed in the array nums. The belt supervisor wants to split it with two cuts into three non-empty consecutive sections so that the three sections have the same XOR of their codes.

A split is described by indices (i, j) with 1 <= i < j <= n - 1: the sections are nums[0..i-1], nums[i..j-1] and nums[j..n-1]. Return how many different pairs (i, j) produce three sections with identical XOR. For example, [2, 2, 2, 2, 2] has exactly 3 such splits.

Trying all pairs is quadratic. Let T be the XOR of the whole array; three equal parts force each part to equal T, which means the prefix XOR at i is T and the prefix XOR at j is 0. Count such pairs in one left-to-right pass with a running counter, in O(n) time and O(1) extra space. The answer needs a 64-bit integer.

Example 1

Input:
nums = [1,1,1]
Output:
1
Explanation:

Only the cuts (1, 2) work, giving three sections that each XOR to 1.

Example 2

Input:
nums = [2,2,2,2,2]
Output:
3
Explanation:

The valid cuts are (1,2), (1,4) and (3,4), each giving three sections with XOR 2.

Constraints

3 ≤ nums.length ≤ 105; 0 ≤ nums[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…