Editorial
After every operation, every value is still one of , , and . Therefore, the final value is also one of these three values.
First, determine the parity of the final value. For integers ,
Thus, modulo , one operation is equivalent to replacing adjacent values by their sum.
After repeating this times, Pascal-triangle coefficients appear. If is the parity of the final value, then
By Lucas's theorem,
is odd if and only if every set bit of is also set in . Equivalently,
Therefore, with , XOR over all positions satisfying . This computes in time.
If , the final value is odd. Since it is one of , , and , the answer must be .
Now suppose . The final value is either or .
If the final value is , the original array cannot contain a . This can be proved by induction on the array length. The claim is trivial for length . For a longer array whose final value is , apply the induction hypothesis to the array after the first operation. Every value after the first operation must be even. Hence every adjacent pair in the original array has the same parity, so all original values have the same parity. If they were all odd, then they would all be , the first operation would produce only s, and the final value would be , a contradiction. Thus all original values are or .
Consequently, if and at least one equals , the answer is .
It remains to handle the case where every is or . Let , so is binary. Since
every value in the entire Difference Pyramid for is exactly twice the corresponding value for . Thus, the final value for is twice the final value for .
Because is binary, its final value is exactly its parity, which is
Compute with the same Lucas-theorem test and print .
We can compute , , and whether a exists in a single pass. The time complexity is and the memory complexity is .
Solution written by GPT5.6