Let and . Let be the XOR of the whole sequence.
A split operation is exactly the insertion of one arbitrary internal value into while keeping both endpoints fixed. If is split into , the newly inserted prefix value is . Conversely, a merge operation deletes exactly one internal prefix value .
If the final sequence has length and every element is , its prefix XOR sequence is
The total XOR is invariant under both operations.
Case
Then must be odd and . The target prefix sequence is .
Filter the original so that only values equal to or remain. Let be the number of maximal runs of equal values in this filtered sequence. Keeping one value from every run gives exactly an alternating sequence . Every other prefix value must be deleted, so the answer is
Case
Let be the number of nonzero values among the internal prefixes . Let be the number of gaps between consecutive zero values in the full prefix sequence.
For , deleting every nonzero internal prefix is sufficient, so the cost is .
Now fix . Keeping every zero prefix never makes an optimum worse. Each gap between two consecutive zeros needs exactly one in the target. Let be the number of gaps that already contain at least one prefix equal to . In such a gap we can keep one occurrence of and save one deletion. In every other gap we must insert one . Therefore the cost is
If , the answer is
We can compute in one scan. Increase the gap index whenever the current prefix is zero. For every nonzero value , store in a hash table the last gap in which was counted and the number of distinct gaps containing . This makes repeated occurrences of inside the same gap count only once.
The expected time complexity is and the memory complexity is .
Solution written by GPT5.6