**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++

`// 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*

## Python3

`# Python program to print the number of elements ` `# greater than k in a subarray of range L-R. ` ` ` `# Structure which will store both ` `# array elements and queries. ` `class` `node: ` ` ` `def` `__init__(` `self` `): ` ` ` `self` `.pos ` `=` `0` ` ` `self` `.l ` `=` `0` ` ` `self` `.r ` `=` `0` ` ` `self` `.val ` `=` `0` ` ` `# Updates the node of BIT array by adding ` `# 1 to it and its ancestors. ` `def` `update(BIT: ` `list` `, n: ` `int` `, idx: ` `int` `): ` ` ` `while` `idx <` `=` `n: ` ` ` `BIT[idx] ` `+` `=` `1` ` ` `idx ` `+` `=` `idx & ` `-` `idx ` ` ` `# Returns the count of numbers of elements ` `# present from starting till idx. ` `def` `query(BIT: ` `list` `, idx: ` `int` `) ` `-` `> ` `int` `: ` ` ` `ans ` `=` `0` ` ` `while` `idx: ` ` ` `ans ` `+` `=` `BIT[idx] ` ` ` `idx ` `-` `=` `idx & ` `-` `idx ` ` ` `return` `ans ` ` ` `# Function to solve the queries offline ` `def` `solveQuery(arr: ` `list` `, n: ` `int` `, QueryL: ` `list` `, ` ` ` `QueryR: ` `list` `, QueryK: ` `list` `, q: ` `int` `): ` ` ` ` ` `# create node to store the elements ` ` ` `# and the queries ` ` ` `a ` `=` `[` `0` `] ` `*` `(n ` `+` `q ` `+` `1` `) ` ` ` `for` `i ` `in` `range` `(n ` `+` `q ` `+` `1` `): ` ` ` `a[i] ` `=` `node() ` ` ` ` ` `# 1-based indexing ` ` ` ` ` `# traverse for all array numbers ` ` ` `for` `i ` `in` `range` `(` `1` `, n ` `+` `1` `): ` ` ` `a[i].val ` `=` `arr[i ` `-` `1` `] ` ` ` `a[i].pos ` `=` `0` ` ` `a[i].l ` `=` `0` ` ` `a[i].r ` `=` `i ` ` ` ` ` `# iterate for all queries ` ` ` `for` `i ` `in` `range` `(n ` `+` `1` `, n ` `+` `q ` `+` `1` `): ` ` ` `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 sorted function used to ` ` ` `# sort node array using comp function. ` ` ` `a ` `=` `[a[` `0` `]] ` `+` `sorted` `(a[` `1` `:], ` ` ` `key ` `=` `lambda` `k: (k.val, k.l), ` ` ` `reverse ` `=` `True` `) ` ` ` ` ` `# Binary Indexed tree with ` ` ` `# initially 0 at all places. ` ` ` `BIT ` `=` `[` `0` `] ` `*` `(n ` `+` `1` `) ` ` ` ` ` `# For storing answers for ` ` ` `# each query( 1-based indexing ). ` ` ` `ans ` `=` `[` `0` `] ` `*` `(q ` `+` `1` `) ` ` ` ` ` `# traverse for numbers and query ` ` ` `for` `i ` `in` `range` `(` `1` `, n ` `+` `q ` `+` `1` `): ` ` ` `if` `a[i].pos !` `=` `0` `: ` ` ` ` ` `# call function to returns answer for each query ` ` ` `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` `i ` `in` `range` `(` `1` `, q ` `+` `1` `): ` ` ` `print` `(ans[i]) ` ` ` `# Driver Code ` `if` `__name__ ` `=` `=` `"__main__"` `: ` ` ` ` ` `arr ` `=` `[` `7` `, ` `3` `, ` `9` `, ` `13` `, ` `5` `, ` `4` `] ` ` ` `n ` `=` `len` `(arr) ` ` ` ` ` `# 1-based indexing ` ` ` `QueryL ` `=` `[` `1` `, ` `2` `] ` ` ` `QueryR ` `=` `[` `4` `, ` `6` `] ` ` ` ` ` `# k for each query ` ` ` `QueryK ` `=` `[` `6` `, ` `8` `] ` ` ` ` ` `# number of queries ` ` ` `q ` `=` `len` `(QueryL) ` ` ` ` ` `# Function call to get ` ` ` `solveQuery(arr, n, QueryL, QueryR, QueryK, q) ` ` ` `# This code is contributed by ` `# sanjeev2552 ` |

*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 for elements greater than K in the given index range using Segment Tree
- XOR of elements in a given range with updates using Fenwick Tree
- Queries for elements having values within the range A to B in the given index range using Segment Tree
- Queries to find the Lower Bound of K from Prefix Sum Array with updates using Fenwick Tree
- Queries for the count of even digit sum elements in the given range using Segment Tree.
- Queries to check whether all the elements in the given range occurs even number of times
- Count of elements having odd number of divisors in index range [L, R] for Q queries
- Array range queries to find the number of perfect square elements with updates
- Binary Indexed Tree : Range Update and Range Queries
- Range Queries to count elements lying in a given Range : MO's Algorithm
- Sum of all array elements less than X and greater than Y for Q queries
- Find the XOR of the elements in the given range [L, R] with the value K for a given set of queries
- Queries for greatest pair sum in the given index range using Segment Tree
- Binary Indexed Tree : Range Updates and Point Queries
- Queries for GCD of all numbers of an array except elements in a given range
- Range Queries for Frequencies of array elements
- Queries for elements having values within the range A to B using MO's Algorithm
- Array range queries for elements with frequency same as value
- Count of elements which are power of 2 in a given range subarray for Q queries
- Queries for counts of array elements with values in given range

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.