Editorial
Let . For every and every remainder, store the sorted indices of elements having that remainder. Each element enters lists, so preprocessing time and memory are .
For , answer a query with two binary searches in the corresponding list. For , since , at most one value can have remainder ; use the list for that exact value.
Each query takes time.
Solution written by GPT5