I am trying to solve this problem https://www.spoj.com/problems/KQUERY/ but i keep getting WA. Here is my code https://ideone.com/8Gknva My idea is for eacch query (l,r) answer the query for (l,n) and then for (r,n) without including r in the second one and then the answer would be difference Now for (l,n) i sort queries in terms of increasing l and at each point i keep updating occurences and sum occurences of elements greater than k using segment tree. For (r,n) same thing but i sort in terms of increasing r. Could someone help me spot the issue with my code.