1544. Subarray XOR Grand Total

Medium3.5 points estimatedBit ManipulationPrefix SumCounting

A quality team records readings in the array nums. For every contiguous, non-empty stretch of readings they compute a check value, the bitwise XOR of all readings inside it, and then add up the check values of all stretches.

Return that grand total. For example, [1, 2, 3] has stretches with check values 1, 2, 3, 3, 1 and 0, so the total is 10.

There are about n squared / 2 stretches, so computing each one is too slow for long inputs. Remember that a stretch XOR equals the XOR of two prefix XOR values (including the empty prefix); a given bit is set in the stretch exactly when those two prefixes disagree on it. For every bit, count how many of the n + 1 prefixes have it set, multiply the number of disagreeing pairs by the bit weight, and sum. Aim for O(n * 20) time and O(1) extra space. The total is below 2^53.

Example 1

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

The six stretches give 1 + 2 + 3 + 3 + 1 + 0 = 10.

Example 2

Input:
nums = [4,4]
Output:
8
Explanation:

The stretches give 4, 4 and 4 ^ 4 = 0, so the total is 8.

Constraints

1 ≤ nums.length ≤ 105; 0 ≤ nums[i] < 220 (the answer is below 253)

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 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,200 ms

Expected complexity

Time
O(n log C)
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…