# Number of elements greater than K in the range L to R using Fenwick Tree (Offline queries)

**Prerequisites: ** Fenwick Tree (Binary Indexed Tree)

Given an array of N numbers, and a number of queries where each query will contain three numbers(l, r and k). The task is to calculate the number of array elements which are greater than K in the subarray[L, R].

**Examples:**

Input: n=6 q=2 arr[ ] = { 7, 3, 9, 13, 5, 4 } Query1: l=1, r=4, k=6 Query2: l=2, r=6, k=8 Output: 3 2 For the first query, [7, 3, 9, 13] represents the subarray from index 1 till 4, in which there are 3 numbers which are greater than k=6 that are {7, 9, 13}. For the second query, there are only two numbers in the query range which are greater than k.

**Naive Approach **is to find the answer for each query by simply traversing the array from index l till r and keep adding 1 to the count whenever the array element is greater than k.

**Time Complexity:** O(n*q)

A **Better Approach** is to use Merge Sort Tree. In this approach, build a Segment Tree with a vector at each node containing all the elements of the sub-range in a sorted order. Answer each query using the segment tree where Binary Search can be used to calculate how many numbers are present in each node whose sub-range lies within the query range which are greater than k.

**Time complexity:** O(q * log(n) * log(n))

An **Efficient Approach** is to solve the problem using offline queries and Fenwick Trees. Below are the steps:

- First store all the array elements and the queries in the same array. For this, we can create a self-structure or class.
- Then sort the structural array in descending order ( in case of collision the query will come first then the array element).
- Process the whole array of structure again, but before that create another BIT array (Binary Indexed Tree) whose query( i ) function will return the count of all the elements which are present in the array till i’th index.
- Initially, fill the whole array with 0.
- Create an answer array, in which the answers of each query are stored.
- Process the array of structure.
- If it is an array element, then update the BIT array with +1 from the index of that element.
- If it is a query, then subtract the
*query(r) – query(l-1)*and this will be the answer for that query which will be stored in answer array at the index corresponding to the query number. - Finally output the answer array.

The key observation here is that since the array of the structure has been sorted in descending order. Whenever we encounter any query only the elements which are greater than ‘k’ comprises the count in the BIT array which is the answer that is needed.

Below is the explanation of structure used in the program:

Pos:stores the order of query. In case of array elements it is kept as 0.

L:stores the starting index of the query’s subarray. In case of array elements it is also 0.

R:stores the ending idex of the query’s subarray. In case of array element it is used to store the position of element in the array.

Val:store ‘k’ of the query and all the array elements.

Below is the implementation of the above approach:

`// C++ program to print the number of elements ` `// greater than k in a subarray of range L-R. ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// Structure which will store both ` `// array elements and queries. ` `struct` `node { ` ` ` `int` `pos; ` ` ` `int` `l; ` ` ` `int` `r; ` ` ` `int` `val; ` `}; ` ` ` `// Boolean comparator that will be used ` `// for sorting the structural array. ` `bool` `comp(node a, node b) ` `{ ` ` ` `// If 2 values are equal the query will ` ` ` `// occur first then array element ` ` ` `if` `(a.val == b.val) ` ` ` `return` `a.l > b.l; ` ` ` ` ` `// Otherwise sorted in descending order. ` ` ` `return` `a.val > b.val; ` `} ` ` ` `// Updates the node of BIT array by adding ` `// 1 to it and its ancestors. ` `void` `update(` `int` `* BIT, ` `int` `n, ` `int` `idx) ` `{ ` ` ` `while` `(idx <= n) { ` ` ` `BIT[idx]++; ` ` ` `idx += idx & (-idx); ` ` ` `} ` `} ` `// Returns the count of numbers of elements ` `// present from starting till idx. ` `int` `query(` `int` `* BIT, ` `int` `idx) ` `{ ` ` ` `int` `ans = 0; ` ` ` `while` `(idx) { ` ` ` `ans += BIT[idx]; ` ` ` ` ` `idx -= idx & (-idx); ` ` ` `} ` ` ` `return` `ans; ` `} ` ` ` `// Function to solve the queries offline ` `void` `solveQuery(` `int` `arr[], ` `int` `n, ` `int` `QueryL[], ` ` ` `int` `QueryR[], ` `int` `QueryK[], ` `int` `q) ` `{ ` ` ` `// create node to store the elements ` ` ` `// and the queries ` ` ` `node a[n + q + 1]; ` ` ` `// 1-based indexing. ` ` ` ` ` `// traverse for all array numbers ` ` ` `for` `(` `int` `i = 1; i <= n; ++i) { ` ` ` `a[i].val = arr[i - 1]; ` ` ` `a[i].pos = 0; ` ` ` `a[i].l = 0; ` ` ` `a[i].r = i; ` ` ` `} ` ` ` ` ` `// iterate for all queries ` ` ` `for` `(` `int` `i = n + 1; i <= n + q; ++i) { ` ` ` `a[i].pos = i - n; ` ` ` `a[i].val = QueryK[i - n - 1]; ` ` ` `a[i].l = QueryL[i - n - 1]; ` ` ` `a[i].r = QueryR[i - n - 1]; ` ` ` `} ` ` ` ` ` `// In-built sort function used to ` ` ` `// sort node array using comp function. ` ` ` `sort(a + 1, a + n + q + 1, comp); ` ` ` ` ` `// Binary Indexed tree with ` ` ` `// initially 0 at all places. ` ` ` `int` `BIT[n + 1]; ` ` ` ` ` `// initially 0 ` ` ` `memset` `(BIT, 0, ` `sizeof` `(BIT)); ` ` ` ` ` `// For storing answers for each query( 1-based indexing ). ` ` ` `int` `ans[q + 1]; ` ` ` ` ` `// traverse for numbers and query ` ` ` `for` `(` `int` `i = 1; i <= n + q; ++i) { ` ` ` `if` `(a[i].pos != 0) { ` ` ` ` ` `// call function to returns answer for each query ` ` ` `int` `cnt = query(BIT, a[i].r) - query(BIT, a[i].l - 1); ` ` ` ` ` `// This will ensure that answer of each query ` ` ` `// are stored in order it was initially asked. ` ` ` `ans[a[i].pos] = cnt; ` ` ` `} ` ` ` `else` `{ ` ` ` `// a[i].r contains the position of the ` ` ` `// element in the original array. ` ` ` `update(BIT, n, a[i].r); ` ` ` `} ` ` ` `} ` ` ` `// Output the answer array ` ` ` `for` `(` `int` `i = 1; i <= q; ++i) { ` ` ` `cout << ans[i] << endl; ` ` ` `} ` `} ` ` ` `// Driver Code ` `int` `main() ` `{ ` ` ` `int` `arr[] = { 7, 3, 9, 13, 5, 4 }; ` ` ` `int` `n = ` `sizeof` `(arr) / ` `sizeof` `(arr[0]); ` ` ` ` ` `// 1-based indexing ` ` ` `int` `QueryL[] = { 1, 2 }; ` ` ` `int` `QueryR[] = { 4, 6 }; ` ` ` ` ` `// k for each query ` ` ` `int` `QueryK[] = { 6, 8 }; ` ` ` ` ` `// number of queries ` ` ` `int` `q = ` `sizeof` `(QueryL) / ` `sizeof` `(QueryL[0]); ` ` ` ` ` `// Function call to get ` ` ` `solveQuery(arr, n, QueryL, QueryR, QueryK, q); ` ` ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

**Output:**

3 2

**Time Complexity:** O(N * log N) where N = (n+q)

**What is offline query?**

In some questions, it is hard to answer queries in any random order. So instead of answering each query separately, store all the queries and then order them accordingly to calculate answer for them efficiently. Store all the answers and then output it in the order it was initially given.

This technique is called *Offline Query*.

**Note:** Instead of Fenwick Tree, segment tree can also be used where each node of the segment tree will store the number of elements inserted till that iteration. The update and query functions will change, rest of the implementation will remain same.

**Necessary Condition For Offline Query: **This technique can be used only when the answer of one query does not depend on the answers of previous queries since after sorting the order of queries may change.

## Recommended Posts:

- Queries to check whether all the elements in the given range occurs even number of times
- Binary Indexed Tree : Range Update and Range Queries
- Range Queries for Frequencies of array elements
- Array range queries for elements with frequency same as value
- Queries for GCD of all numbers of an array except elements in a given range
- Binary Indexed Tree : Range Updates and Point Queries
- Queries for counts of array elements with values in given range
- Two Dimensional Binary Indexed Tree or Fenwick Tree
- Order statistic tree using fenwick tree (BIT)
- Binary Indexed Tree or Fenwick Tree
- Range Queries to Find number of sub-arrays with a given xor
- Count number of indices such that s[i] = s[i+1] : Range queries
- Count smaller elements on right side and greater elements on left side using Binary Index Tree
- Array range queries over range queries
- Queries for number of elements on right and left

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.