Write for the result of applying one operation to a sequence , and let and .
As we move right, the set of preceding elements only grows, so is nondecreasing. Applying the operation to a nondecreasing sequence gives and makes every difference between adjacent elements either or .
A prefix ending at therefore contains every integer from through . Consequently,
The result has the same property, so every subsequent operation follows the same rule. Equivalently, prepend , increase each retained old element by , and discard the last old element.
We only need to precompute and to answer a query.
To compute , scan the original sequence from left to right, recording which values have appeared and maintaining the current . Store that value in before inserting . Values at least do not need to be recorded.
Compute with another left-to-right scan. If the current is , first set , then increase by only when .
Preprocessing takes time, and each query takes time. The total time complexity is . Processing queries as they are read gives an space complexity.
Proof
Adding an element to a set cannot remove any value already present, so its cannot decrease. Thus, is nondecreasing for every original sequence .
Let be the of the first elements of a nondecreasing sequence . If , adding leaves absent, so the does not change. If , all preceding elements are at most , so has not appeared. After adding , the new is exactly . Therefore, and every difference is either or .
Solution written by GPT6
Any prefix of a nondecreasing sequence that starts at and increases by at most contains all integers from through its last value, and no larger values. Its is therefore exactly one greater than its last value. This proves and .
The first two values of the transformed sequence, when both exist, are , and its remaining adjacent differences equal the corresponding differences in the original sequence. The same property is therefore preserved. After applying this rule times, the first positions have values , while a later position contains . At , this is also because . If more operations are applied than there are positions, the already established value at each position remains unchanged. Hence, the query formula holds for every valid .
While computing with a presence array, the never decreases and never exceeds . The total number of increments is therefore . Computing also requires only one scan, so preprocessing takes time.