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 that 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.
Algorithm:
- Initialize the array and its size
- Define a function countElements() to count the number of elements greater than k in subarray[l, r]:
- Initialize a count variable to 0
- Traverse the subarray from index l to r
If the element at the current index is greater than k, increment the count by 1
- Return the count
- For each query, get the values of l, r and k
- Call the function countElements() for the current query
- Print the result returned by the function
Below is the implementation of the approach:
C++
#include<bits/stdc++.h>
using namespace std;
int countElements( int arr[], int n, int l, int r, int k) {
int count = 0;
for ( int i = l; i <= r; i++) {
if (arr[i] > k) {
count++;
}
}
return count;
}
int main() {
int arr[] = { 7, 3, 9, 13, 5, 4 };
int n = sizeof (arr) / sizeof (arr[0]);
int l = 1, r = 4, k = 6;
int ans = countElements(arr, n, l-1, r-1, k);
cout << ans << endl;
l = 2, r = 6, k = 8;
ans = countElements(arr, n, l-1, r-1, k);
cout << ans << endl;
return 0;
}
|
Java
import java.util.*;
public class GFG {
public static int countElements( int [] arr, int n, int l, int r, int k) {
int count = 0 ;
for ( int i = l; i <= r; i++) {
if (arr[i] > k) {
count++;
}
}
return count;
}
public static void main(String[] args) {
int [] arr = { 7 , 3 , 9 , 13 , 5 , 4 };
int n = arr.length;
int l = 1 , r = 4 , k = 6 ;
int ans = countElements(arr, n, l- 1 , r- 1 , k);
System.out.println(ans);
l = 2 ; r = 6 ; k = 8 ;
ans = countElements(arr, n, l- 1 , r- 1 , k);
System.out.println(ans);
}
}
|
Python3
def count_elements(arr, l, r, k):
count = 0
for i in range (l, r + 1 ):
if arr[i] > k:
count + = 1
return count
if __name__ = = "__main__" :
arr = [ 7 , 3 , 9 , 13 , 5 , 4 ]
n = len (arr)
l, r, k = 1 , 4 , 6
ans = count_elements(arr, l - 1 , r - 1 , k)
print (ans)
l, r, k = 2 , 6 , 8
ans = count_elements(arr, l - 1 , r - 1 , k)
print (ans)
|
C#
using System;
class GFG {
static int CountElements( int [] arr, int l, int r, int k)
{
int count = 0;
for ( int i = l; i <= r; i++) {
if (arr[i] > k) {
count++;
}
}
return count;
}
static void Main( string [] args)
{
int [] arr = { 7, 3, 9, 13, 5, 4 };
int n = arr.Length;
int l = 1, r = 4, k = 6;
int ans = CountElements(arr, l - 1, r - 1, k);
Console.WriteLine(ans);
l = 2;
r = 6;
k = 8;
ans = CountElements(arr, l - 1, r - 1, k);
Console.WriteLine(ans);
}
}
|
Javascript
function countElements(arr, l, r, k) {
let count = 0;
for (let i = l; i <= r; i++) {
if (arr[i] > k) {
count++;
}
}
return count;
}
const arr = [7, 3, 9, 13, 5, 4];
const n = arr.length;
const l1 = 1, r1 = 4, k1 = 6;
const ans1 = countElements(arr, l1 - 1, r1 - 1, k1);
console.log(ans1);
const l2 = 2, r2 = 6, k2 = 8;
const ans2 = countElements(arr, l2 - 1, r2 - 1, k2);
console.log(ans2);
|
Time Complexity: O(n*q)
Auxiliary Space: O(1) as no extra space has been used.
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 index 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++
#include <bits/stdc++.h>
using namespace std;
struct node {
int pos;
int l;
int r;
int val;
};
bool comp(node a, node b)
{
if (a.val == b.val)
return a.l > b.l;
return a.val > b.val;
}
void update( int * BIT, int n, int idx)
{
while (idx <= n) {
BIT[idx]++;
idx += idx & (-idx);
}
}
int query( int * BIT, int idx)
{
int ans = 0;
while (idx) {
ans += BIT[idx];
idx -= idx & (-idx);
}
return ans;
}
void solveQuery( int arr[], int n, int QueryL[],
int QueryR[], int QueryK[], int q)
{
node a[n + q + 1];
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;
}
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];
}
sort(a + 1, a + n + q + 1, comp);
int BIT[n + 1];
memset (BIT, 0, sizeof (BIT));
int ans[q + 1];
for ( int i = 1; i <= n + q; ++i) {
if (a[i].pos != 0) {
int cnt = query(BIT, a[i].r) - query(BIT, a[i].l - 1);
ans[a[i].pos] = cnt;
}
else {
update(BIT, n, a[i].r);
}
}
for ( int i = 1; i <= q; ++i) {
cout << ans[i] << endl;
}
}
int main()
{
int arr[] = { 7, 3, 9, 13, 5, 4 };
int n = sizeof (arr) / sizeof (arr[0]);
int QueryL[] = { 1, 2 };
int QueryR[] = { 4, 6 };
int QueryK[] = { 6, 8 };
int q = sizeof (QueryL) / sizeof (QueryL[0]);
solveQuery(arr, n, QueryL, QueryR, QueryK, q);
return 0;
}
|
Java
import java.util.*;
public class Main {
static class Node {
int pos;
int l;
int r;
int val;
public Node() {
pos = 0 ;
l = 0 ;
r = 0 ;
val = 0 ;
}
}
public static void update( int [] BIT, int n, int idx) {
while (idx <= n) {
BIT[idx] += 1 ;
idx += idx & -idx;
}
}
public static int query( int [] BIT, int idx) {
int ans = 0 ;
while (idx > 0 ) {
ans += BIT[idx];
idx -= idx & -idx;
}
return ans;
}
public static void solveQuery( int [] arr, int n, int [] QueryL,
int [] QueryR, int [] QueryK, int q) {
Node[] a = new Node[n + q + 1 ];
for ( int i = 0 ; i < n + q + 1 ; i++) {
a[i] = new Node();
}
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;
}
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 ];
}
Arrays.sort(a, 1 , n + q + 1 , new Comparator<Node>() {
public int compare(Node o1, Node o2) {
if (o1.val != o2.val)
return Integer.compare(o2.val, o1.val);
return Integer.compare(o1.l, o2.l);
}
});
int [] BIT = new int [n + 1 ];
int [] ans = new int [q + 1 ];
for ( int i = 1 ; i <= n + q; i++) {
if (a[i].pos != 0 ) {
int cnt = query(BIT, a[i].r) - query(BIT, a[i].l - 1 );
ans[a[i].pos] = cnt;
} else {
update(BIT, n, a[i].r);
}
}
for ( int i = 1 ; i <= q; i++) {
System.out.println(ans[i]);
}
}
public static void main (String[] args) {
int [] arr = { 7 , 3 , 9 , 13 , 5 , 4 };
int n = arr.length;
int [] QueryL = { 1 , 2 };
int [] QueryR = { 4 , 6 };
int [] QueryK = { 6 , 8 };
int q = QueryL.length;
solveQuery(arr, n, QueryL, QueryR, QueryK, q);
}}
|
Python3
class node:
def __init__( self ):
self .pos = 0
self .l = 0
self .r = 0
self .val = 0
def update(BIT: list , n: int , idx: int ):
while idx < = n:
BIT[idx] + = 1
idx + = idx & - idx
def query(BIT: list , idx: int ) - > int :
ans = 0
while idx:
ans + = BIT[idx]
idx - = idx & - idx
return ans
def solveQuery(arr: list , n: int , QueryL: list ,
QueryR: list , QueryK: list , q: int ):
a = [ 0 ] * (n + q + 1 )
for i in range (n + q + 1 ):
a[i] = node()
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
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 ]
a = [a[ 0 ]] + sorted (a[ 1 :],
key = lambda k: (k.val, k.l),
reverse = True )
BIT = [ 0 ] * (n + 1 )
ans = [ 0 ] * (q + 1 )
for i in range ( 1 , n + q + 1 ):
if a[i].pos ! = 0 :
cnt = query(BIT, a[i].r) - query(BIT, a[i].l - 1 )
ans[a[i].pos] = cnt
else :
update(BIT, n, a[i].r)
for i in range ( 1 , q + 1 ):
print (ans[i])
if __name__ = = "__main__" :
arr = [ 7 , 3 , 9 , 13 , 5 , 4 ]
n = len (arr)
QueryL = [ 1 , 2 ]
QueryR = [ 4 , 6 ]
QueryK = [ 6 , 8 ]
q = len (QueryL)
solveQuery(arr, n, QueryL, QueryR, QueryK, q)
|
C#
using System;
using System.Collections.Generic;
struct Node
{
public int pos;
public int l;
public int r;
public int val;
}
class Program {
class NodeComparer : IComparer<Node> {
public int Compare(Node a, Node b)
{
if (a.val == b.val)
return a.l > b.l ? -1 : 1;
return a.val > b.val ? -1 : 1;
}
}
static void Update( int [] BIT, int n, int idx)
{
while (idx <= n) {
BIT[idx]++;
idx += idx & (-idx);
}
}
static int Query( int [] BIT, int idx)
{
int ans = 0;
while (idx > 0) {
ans += BIT[idx];
idx -= idx & (-idx);
}
return ans;
}
static void SolveQuery( int [] arr, int n, int [] QueryL,
int [] QueryR, int [] QueryK,
int q)
{
Node[] a = new Node[n + q + 1];
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;
}
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];
}
Array.Sort(a, 1, n + q, new NodeComparer());
int [] BIT = new int [n + 1];
Array.Clear(BIT, 0, BIT.Length);
int [] ans = new int [q + 1];
for ( int i = 1; i <= n + q; ++i) {
if (a[i].pos != 0) {
int cnt = Query(BIT, a[i].r)
- Query(BIT, a[i].l - 1);
ans[a[i].pos] = cnt;
}
else {
Update(BIT, n, a[i].r);
}
}
for ( int i = 1; i <= q; ++i) {
Console.WriteLine(ans[i]);
}
}
static void Main()
{
int [] arr = { 7, 3, 9, 13, 5, 4 };
int n = arr.Length;
int [] QueryL = { 1, 2 };
int [] QueryR = { 4, 6 };
int [] QueryK = { 6, 8 };
int q = QueryL.Length;
SolveQuery(arr, n, QueryL, QueryR, QueryK, q);
}
}
|
Javascript
class Node {
constructor(pos, l, r, val) {
this .pos = pos;
this .l = l;
this .r = r;
this .val = val;
}
}
function comp(a, b) {
if (a.val === b.val)
return a.l > b.l;
return a.val > b.val;
}
function update(BIT, n, idx) {
while (idx <= n) {
BIT[idx]++;
idx += idx & (-idx);
}
}
function query(BIT, idx) {
let ans = 0;
while (idx) {
ans += BIT[idx];
idx -= idx & (-idx);
}
return ans;
}
function solveQuery(arr, n, QueryL, QueryR, QueryK, q) {
let a = [];
for (let i = 0; i < n; i++) {
a.push( new Node(0, 0, i + 1, arr[i]));
}
for (let i = 0; i < q; i++) {
a.push( new Node(i + 1, QueryL[i], QueryR[i], QueryK[i]));
}
a.sort(comp);
let BIT = [];
for (let i = 0; i <= n; i++) {
BIT.push(0);
}
let ans = [];
for (let i = 0; i < a.length; i++) {
if (a[i].pos !== 0) {
let cnt = query(BIT, a[i].r) - query(BIT, a[i].l - 1);
ans[a[i].pos] = cnt;
}
|
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.
Last Updated :
29 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...