1541. Best XOR Stretch

Medium3.5 points estimatedTrieBit ManipulationPrefix Sum

A sensor logs a stream of 16-bit status words in the array nums. The signature of a contiguous, non-empty stretch of the log is the bitwise XOR of all words inside it. A technician wants the stretch whose signature is as large as possible.

Return the maximum signature over all non-empty contiguous subarrays of nums. For example, [5, 1, 6] has stretches with signatures 5, 1, 6, 4, 7 and 2, so the answer is 7.

Checking every stretch takes quadratic time, which is too slow for a long log. Use the fact that a stretch signature is the XOR of two prefix XOR values, and find the best partner for each prefix by walking a binary trie from the high bit to the low bit, preferring the opposite bit. The intended running time is O(n * 16) with O(n * 16) memory. The answer always fits in a 32-bit integer.

Example 1

Input:
nums = [5,1,6]
Output:
7
Explanation:

The six stretches have signatures 5, 1, 6, 4, 7 and 2, and the largest is 7.

Example 2

Input:
nums = [1,2,4,8]
Output:
15
Explanation:

The whole log gives 1^2^4^8 = 15, which is the largest possible.

Constraints

1 ≤ nums.length ≤ 105; 0 ≤ nums[i] < 216

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 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms

Expected complexity

Time
O(n log C)
Space
O(n log C)

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…