Ferume asked me if I can solve this faster than O(nnlogn). And it turns out I can! Thanks to him for creating this problem and not letting it live with boring solution.
Let S be a multiset containing non-negative integers. You can do the following operation on S arbitrary number of times (possibly zero): choose x such that there are at least two occurrences of x in S, delete one of the occurrences but insert one occurrence of (x−1) or (x+1) instead (you can insert (x−1) only if it is non-negative). Let F(S) be the maximum mex(S) you can achieve with these operations. Here mex(S) is the minimal non-negative integer which is not present in S.
You are given an array a of length n and q queries \[l;r]. For each query, find F(a_l,a_l+1,…,a_r).
The first line contains two integers n, q (1≤n,q≤5⋅105) --- the size of array and the number of queries.
The second line contains the array a_1,a_2,…,a_n itself (0≤a_i≤5⋅105).
Next q lines contain queries l_i r_i (1≤l_i≤r_i≤n).
Print answers to queries in the order they are listed in input on separate lines.