#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;
struct Merge_Sort_Tree {
vector<set<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].insert({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.insert({i.S, i.F});
}
set<pair<int, int>> em;
set<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;
set<pair<int, int>> Cur;
for(auto &i: Left) mp[i.S] += i.F;
for(auto &i: Right) mp[i.S] += i.F;
for(auto &i: mp) Cur.insert({i.S, i.F});
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];
}
st1.build(1, 0 , n - 1, v);
int l, r, k;
while(q--) {
cin >> l >> r; --l, --r;
k = (r - l + 1) / 3;
auto st = st1.query(1, 0, n - 1, l, r);
if(st.rbegin()->F > k) {
auto it = st.lower_bound(make_pair(l, r));
int ans = INT_MAX;
while(it != st.end()) {
ans = min(ans, it->S);
++it;
}
cout << ans << endl;
}
else cout << -1 << 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;
}