Editorial
Create two distinct vertices and for every integer from to . Also create two sentinel vertices and for the left and right ends.
For the current sequence , store the following undirected edges.
- Connect with .
- For every , connect with .
- Connect with .
Every vertex has degree exactly , so its unique neighbor can be stored in an array .
If two consecutive sequence values are , their adjacency is represented by the edge . After both reversing and negating that part, the corresponding consecutive values become . Their edge is , which is the same undirected edge. Therefore, every edge strictly inside the queried interval remains unchanged.
Let the query endpoints be , and define
Before the query, the edges and exist. Remove them and add
These two changes exactly replace the first value by and the last value by . Thus, each query changes only four array entries.
To reconstruct the final sequence, start at . Since , the first value is . If the current value is and , the next value is .
Initialization and reconstruction take time, while each query takes time. The total time complexity is and the memory complexity is .
Solution written by GPT5.6