Kth Number
Difficulty: Hard

You are given an array of $N$ positive integers, $A_1, A_2, \ldots, A_n$. You have to answer $Q$ queries. Each query consists of two integers $L$ and $K$.

For each query, you have to consider all the elements of array greater than or equal to $L$, in _original order of occurrence_ in array $A$ and then find the $K^{th}$ element from the selected elements. It is guaranteed that the $K^{th}$ number will exist.

Input Format:
The first line contains two integers $N$ and $Q$. The next line contains $N$ space separated integers, representing the array, $A_1,\ A_2,\ \ldots,\ A_n$.

Each of the next $Q$ lines contain two space separated integers $L$ and $K$.

**Constraints**:

$1\le N \le 10^5$

$1 \le Q \le 10^5$

$1 \le A_i \le 10^5$

$1 \le L \le 10^5$

$1 \le K \le 10^5$  

**Note on TL:**  C/cpp 1sec, Java 3sec

Output Format:
Output $Q$ lines, the answer for each query.

Sample Input:
    10 4
    1 9 2 8 3 7 4 6 5 10
    4 4
    3 2
    1 6
    8 1

Sample Output:
    4
    8
    7
    9

Python 3 starter code:


Reference solution (C++):
    #include <bits/stdc++.h>
    using namespace std;
    vector <int> indices[100005]; int arr[100005]; 
    struct node
    {
        node * first; node * second; int count; 
        node (node * a, node * b, int c){first=a; second=b; count=c;}
    };
    node * root = new node (NULL, NULL, 0); 
    node * x[100005]; 
    node * insert (int start, int end, node * r, int num)
    {
        if (start<=num && end>=num)
        {
            if (r==NULL) r=new node (NULL, NULL, 0); 
            if (start==end)
            {
                return new node (r->first, r->second, r->count+1); 
            }
            node * n=insert(start, (start+end)/2, r->first, num);
            node * m=insert((start+end)/2+1, end, r->second, num);
            int z= (n==NULL)?0:n->count;
            int zz=(m==NULL)?0:m->count;
            return new node (n, m, z+zz); 
        }
        return r; 
    }
    int query (int start, int end, node * a, int kth)
    {
        if (start==end) return start;
        int z=(a->first==NULL)?0:a->first->count; 
        if (z>=kth)
        {
            return query(start, (start+end)/2, a->first, kth); 
        }
        else return query((start+end)/2+1, end, a->second, kth-z); 
    }
    int main()
    {
        int a,b; cin >> a >> b;
        for (int g=1; g<=a; g++)
        {
            int c; cin >> c; arr[g]=c; indices[c].push_back(g); 
        }
        x[100001]=root; 
        for (int g=100000; g>=1; g--)
        {
            x[g]=x[g+1]; 
            for (int y=0; y<indices[g].size(); y++)
            {
                x[g]=insert(1, 100000, x[g], indices[g][y]); 
            }
        }
        for (int g=0; g<b; g++)
        {
            int above, kth; cin >> above >> kth;
            cout << arr[query(1, 100000, x[above], kth)]<< '\n'; 
        }
        return 0; 
    }