➤ Problem Link : DQUERY
👉 Hint : Sort with custom comparator
✅ C++ Solution :
#include<bits/stdc++.h> using namespace std; int blk_size; struct query { int lt,rt,ind; }; bool comp(query x,query y) { if(x.lt/blk_size != y.lt/blk_size) return x.lt/blk_size < y.lt/blk_size; return x.rt<y.rt; } int main() { int n,q,l,m; scanf("%d",&n); blk_size=sqrt(n); int arr[n],cnt[1001010],qans=0; for(int i=0;i<n;i++) scanf("%d",&arr[i]); memset(cnt,0,sizeof(cnt)); scanf("%d",&q); query v[q]; int ans[q]; for(int i=0;i<q;i++) { scanf("%d %d",&l,&m); v[i].lt=l-1; v[i].rt=m-1; v[i].ind=i; } sort(v,v+q,comp); int mo_l=0; int mo_r=-1; int curr_l; int curr_r; for(int i=0;i<q;i++) { curr_l=v[i].lt; curr_r=v[i].rt; while(mo_r < curr_r) { ++mo_r; cnt[arr[mo_r]]++; if(cnt[arr[mo_r]]==1) qans++; } while(mo_r >curr_r) { cnt[arr[mo_r]]--; if(cnt[arr[mo_r]]==0) qans--; mo_r--; } while(mo_l > curr_l) { --mo_l; cnt[arr[mo_l]]++; if(cnt[arr[mo_l]]==1) qans++; } while(mo_l < curr_l) { cnt[arr[mo_l]]--; if(cnt[arr[mo_l]]==0) qans--; mo_l++; } ans[v[i].ind]=qans; } for(int i=0;i<q;i++) printf("%d\n",ans[i]); }
Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook.
😇Happy Learning!!