#include<bits/stdc++.h>
#define endl '\n'
#define F first
#define S second
#define pb push_back
#define yes cout<<"YES\n"
#define no cout<<"NO\n"
#define all(x) x.begin(),x.end()
#define allr(x) x.rbegin(),x.rend()
#define error1(x) cerr<<#x<<" = "<<(x)<<endl
#define error2(a,b) cerr<<"("<<#a<<", "<<#b<<") = ("<<(a)<<", "<<(b)<<")\n";
#define coutall(v) for(auto &it: v) cout << it << " "; cout << endl;
using namespace std;
using ll = long long;
using ld = long double;
const int N = 3e5 + 3;
int k, ans;
struct Merge_Sort_Tree {
vector<vector<pair<int, int>>> t;
Merge_Sort_Tree() {
t.resize(4 * N, {});
}
void build(int node, int st, int en, vector<int> &arr) { //=> O(N log N)
t[node].clear();
if (st == en) {
t[node].pb({1, arr[st]});
return;
}
int mid = (st + en) >> 1;
build(node << 1, st, mid, arr); // divide left side
build(node << 1 | 1, mid + 1, en, arr); // divide right side
// Merging left and right portion
auto &Cur = t[node];
auto &Left = t[node << 1];
auto &Right = t[node << 1 | 1];
map<int, int> mp;
for(auto &i: Left) mp[i.S] += i.F;
for(auto &i: Right) mp[i.S] += i.F;
for(auto &i: mp) Cur.pb({i.S, i.F});
}
vector<pair<int, int>> em;
vector<pair<int, int>> query(int node, int st, int en, int l, int r) { //=> O(log N * log N)
// assert(l <= r); // <==
if (st > r || en < l) { // No overlapping and out of range
return em; // <== careful
}
if (l <= st && en <= r) { // Complete overlapped (l-r in range)
return t[node];
}
// Partial overlapping
int mid = (st + en) >> 1;
auto Left = query(node << 1, st, mid, l, r);
auto Right = query(node << 1 | 1, mid + 1, en, l, r);
map<int, int> mp;
for(auto &i: Left) mp[i.S] += i.F;
for(auto &i: Right) mp[i.S] += i.F;
vector<pair<int, int>> Cur;
// cout << "===== " << node << " =====" << endl;
for(auto &i: mp) {
// cout << i.F << " " << i.S << endl;
if(i.S > k) ans = min(ans, i.F);
else Cur.pb({i.S, i.F}); // {cnt, val}
}
return Cur;
}
} st1;
void solve() {
int n, q;
cin >> n >> q;
vector<int> v(n);
for (int i = 0; i < n; i++) {
cin >> v[i];
}
int all = INT_MAX;
st1.build(1, 0, n - 1, v);
auto &vec = st1.t[1];
k = (n - 1 + 1) / 3;
for(auto &i: vec) if(i.F > k) all = min(all, i.S);
int l, r;
while(q--) {
cin >> l >> r; --l, --r;
k = (r - l + 1) / 3;
ans = INT_MAX;
st1.query(1, 0, n - 1, l, r);
if(l == 0 && r == n - 1) ans = all; // <== pre cal
if(ans == INT_MAX) cout << -1 << endl;
else cout << ans << endl;
}
return;
}
signed main() {
ios::sync_with_stdio(false); cin.tie(0);
int tc = 1;
// cin >> tc;
for (int t = 1; t <= tc; t++) {
// cout << "Case " << t << ": ";
solve();
}
return 0;
}