# Numbsubarrayer of elements less than or equal to a given number in a given

Given an array ‘a[]’ and number of queries q. Each query can be represented by l, r, x. Your task is to print the number of elements less than or equal to x in the subarray represented by l to r. Examples:

```Input : arr[] = {2, 3, 4, 5}
q = 2
0 3 5
0 2 2
Output : 4
1
Number of elements less than or equal to
5 in arr[0..3] is 4 (all elements)

Number of elements less than or equal to
2 in arr[0..2] is 1 (only 2)```

Naive approach The naive approach for each query traverse the subarray and count the number of elements which are in the given range.

Efficient Approach The idea is to use-Binary Index Tree. Note in the following steps x is the number according to which you have to find the elements and the subarray is represented by l, r. Step 1: Sort the array in ascending order. Step 2: Sort the queries according to x in ascending order, initialize bit array as 0. Step 3: Start from the first query and traverse the array till the value in the array is less than equal to x. For each such element update the BIT with value equal to 1 Step 4: Query the BIT array in the range l to r

## CPP

 `// C++ program to answer queries to count number` `// of elements smaller than or equal to x.` `#include` `using` `namespace` `std;` ` `  `// structure to hold queries` `struct` `Query` `{` `    ``int` `l, r, x, idx;` `};` ` `  `// structure to hold array` `struct` `ArrayElement` `{` `    ``int` `val, idx;` `};` ` `  `// bool function to sort queries according to k` `bool` `cmp1(Query q1, Query q2)` `{` `    ``return` `q1.x < q2.x;` `}` ` `  `// bool function to sort array according to its value` `bool` `cmp2(ArrayElement x, ArrayElement y)` `{` `    ``return` `x.val < y.val;` `}` ` `  `// updating the bit array` `void` `update(``int` `bit[], ``int` `idx, ``int` `val, ``int` `n)` `{` `    ``for` `(; idx<=n; idx +=idx&-idx)` `        ``bit[idx] += val;` `}` ` `  `// querying the bit array` `int` `query(``int` `bit[], ``int` `idx, ``int` `n)` `{` `    ``int` `sum = 0;` `    ``for` `(; idx > 0; idx -= idx&-idx)` `        ``sum += bit[idx];` `    ``return` `sum;` `}` ` `  `void` `answerQueries(``int` `n, Query queries[], ``int` `q,` `                              ``ArrayElement arr[])` `{` `    ``// initialising bit array` `    ``int` `bit[n+1];` `    ``memset``(bit, 0, ``sizeof``(bit));` ` `  `    ``// sorting the array` `    ``sort(arr, arr+n, cmp2);` ` `  `    ``// sorting queries` `    ``sort(queries, queries+q, cmp1);` ` `  `    ``// current index of array` `    ``int` `curr = 0;` ` `  `    ``// array to hold answer of each Query` `    ``int` `ans[q];` ` `  `    ``// looping through each Query` `    ``for` `(``int` `i=0; i

## Java

 `// Java program to answer queries to count number` `// of elements smaller than or equal to x.`   `import` `java.util.*;`   `// structure to hold queries` `class` `Query` `{` `    ``int` `l, r, x, idx;`   `    ``public` `Query(``int` `l, ``int` `r, ``int` `x, ``int` `idx) {` `        ``this``.l = l;` `        ``this``.r = r;` `        ``this``.x = x;` `        ``this``.idx = idx;` `    ``}` `}`   `// structure to hold array` `class` `ArrayElement ``implements` `Comparable` `{` `    ``int` `val, idx;`   `    ``public` `ArrayElement(``int` `val, ``int` `idx) {` `        ``this``.val = val;` `        ``this``.idx = idx;` `    ``}`   `    ``// bool function to sort array according to its value` `    ``public` `int` `compareTo(ArrayElement other) {` `        ``return` `Integer.compare(``this``.val, other.val);` `    ``}` `}`   `public` `class` `GFG` `{` `    ``// bool function to sort queries according to k` `    ``static` `boolean` `cmp1(Query q1, Query q2)` `    ``{` `        ``return` `q1.x < q2.x;` `    ``}`   `    ``// updating the bit array` `    ``static` `void` `update(``int` `bit[], ``int` `idx, ``int` `val, ``int` `n)` `    ``{` `        ``for` `(; idx<=n; idx +=idx&-idx)` `            ``bit[idx] += val;` `    ``}`   `    ``// querying the bit array` `    ``static` `int` `query(``int` `bit[], ``int` `idx, ``int` `n)` `    ``{` `        ``int` `sum = ``0``;` `        ``for` `(; idx > ``0``; idx -= idx&-idx)` `            ``sum += bit[idx];` `        ``return` `sum;` `    ``}`   `    ``static` `void` `answerQueries(``int` `n, Query queries[], ``int` `q,` `                              ``ArrayElement arr[])` `    ``{` `        ``// initialising bit array` `        ``int` `bit[] = ``new` `int``[n+``1``];` `        ``Arrays.fill(bit, ``0``);`   `        ``// sorting the array` `        ``Arrays.sort(arr);`   `        ``// sorting queries` `        ``Arrays.sort(queries, (q1, q2) -> Integer.compare(q1.x, q2.x));`   `        ``// current index of array` `        ``int` `curr = ``0``;`   `        ``// array to hold answer of each Query` `        ``int` `ans[] = ``new` `int``[q];`   `        ``// looping through each Query` `        ``for` `(``int` `i=``0``; i

## Python3

 `from` `functools ``import` `cmp_to_key` `import` `bisect`   `# structure to hold queries` `class` `Query:` `    ``def` `__init__(``self``, l, r, x, idx):` `        ``self``.l ``=` `l` `        ``self``.r ``=` `r` `        ``self``.x ``=` `x` `        ``self``.idx ``=` `idx` `  `  `# structure to hold array` `class` `ArrayElement:` `    ``def` `__init__(``self``, val, idx):` `        ``self``.val ``=` `val` `        ``self``.idx ``=` `idx` `  `  `# bool function to sort queries according to k` `def` `cmp1(q1, q2):` `    ``if` `q1.x !``=` `q2.x:` `        ``return` `q1.x ``-` `q2.x` `    ``else``:` `        ``return` `q1.r ``-` `q2.r` `  `  `# bool function to sort array according to its value` `def` `cmp2(x, y):` `    ``if` `x.val !``=` `y.val:` `        ``return` `x.val ``-` `y.val` `    ``else``:` `        ``return` `x.idx ``-` `y.idx` `  `  `# updating the bit array` `def` `update(bit, idx, val, n):` `    ``while` `idx <``=` `n:` `        ``bit[idx] ``+``=` `val` `        ``idx ``+``=` `idx & ``-``idx` `  `  `# querying the bit array` `def` `query(bit, idx, n):` `    ``sum` `=` `0` `    ``while` `idx > ``0``:` `        ``sum` `+``=` `bit[idx]` `        ``idx ``-``=` `idx & ``-``idx` `    ``return` `sum` `  `  `def` `answerQueries(n, queries, q, arr):` `    ``# initialising bit array` `    ``bit ``=` `[``0``] ``*` `(n ``+` `1``)` `  `  `    ``# sorting the array` `    ``arr ``=` `sorted``(arr, key``=``cmp_to_key(cmp2))` `  `  `    ``# sorting queries` `    ``queries ``=` `sorted``(queries, key``=``cmp_to_key(cmp1))` `  `  `    ``# current index of array` `    ``curr ``=` `0` `  `  `    ``# array to hold answer of each Query` `    ``ans ``=` `[``0``] ``*` `q` `  `  `    ``# looping through each Query` `    ``for` `i ``in` `range``(q):` `        ``# traversing the array values till it` `        ``# is less than equal to Query number` `        ``while` `curr < n ``and` `arr[curr].val <``=` `queries[i].x:` `            ``# updating the bit array for the array index` `            ``update(bit, arr[curr].idx``+``1``, ``1``, n)` `            ``curr ``+``=` `1` `  `  `        ``# Answer for each Query will be number of` `        ``# values less than equal to x upto r minus` `        ``# number of values less than equal to x` `        ``# upto l-1` `        ``ans[queries[i].idx] ``=` `query(bit, queries[i].r``+``1``, n) ``-` `query(bit, queries[i].l, n)` `  `  `    ``# printing answer for each Query` `    ``for` `i ``in` `range``(q):` `        ``print``(ans[i])` `  `  `# driver function` `if` `__name__ ``=``=` `'__main__'``:` `    ``# size of array` `    ``n ``=` `4` `  `  `    ``# initialising array value and index` `    ``arr ``=` `[ArrayElement(``2``, ``0``), ArrayElement(``3``, ``1``), ArrayElement(``4``, ``2``), ArrayElement(``5``, ``3``)]` `  `  `    ``# number of queries` `    ``q ``=` `2` `    ``queries ``=` `[Query(``0``, ``2``, ``2``, ``0``), Query(``0``, ``3``, ``5``, ``1``)]` `  `  `    ``answerQueries(n, queries, q, arr)`

## C#

 `// C# program to answer queries to count number` `// of elements smaller than or equal to x.` `using` `System;` `using` `System.Linq;`   `// structure to hold queries` `class` `Query` `{` `    ``public` `int` `l, r, x, idx;`   `    ``public` `Query(``int` `l, ``int` `r, ``int` `x, ``int` `idx) {` `        ``this``.l = l;` `        ``this``.r = r;` `        ``this``.x = x;` `        ``this``.idx = idx;` `    ``}` `}`   `// structure to hold array` `class` `ArrayElement : IComparable` `{` `    ``public` `int` `val, idx;` `    `  `    ``public` `ArrayElement(``int` `val, ``int` `idx) {` `        ``this``.val = val;` `        ``this``.idx = idx;` `    ``}`   `    ``// bool function to sort array according to its value` `    ``public` `int` `CompareTo(ArrayElement other) {` `        ``return` `this``.val.CompareTo(other.val);` `    ``}` `}`   `public` `class` `GFG` `{` `    ``// bool function to sort queries according to k` `    ``static` `bool` `cmp1(Query q1, Query q2)` `    ``{` `        ``return` `q1.x < q2.x;` `    ``}` `    ``// updating the bit array` `    ``static` `void` `update(``int``[] bit, ``int` `idx, ``int` `val, ``int` `n)` `    ``{` `        ``for` `(; idx <= n; idx += idx & -idx)` `            ``bit[idx] += val;` `    ``}`   `    ``// querying the bit array` `    ``static` `int` `query(``int``[] bit, ``int` `idx, ``int` `n)` `    ``{` `        ``int` `sum = 0;` `        ``for` `(; idx > 0; idx -= idx & -idx)` `            ``sum += bit[idx];` `        ``return` `sum;` `    ``}`   `    ``static` `void` `answerQueries(``int` `n, Query[] queries, ``int` `q, ArrayElement[] arr)` `    ``{` `        ``// initialising bit array` `        ``int``[] bit = ``new` `int``[n + 1];` `        ``Array.Fill(bit, 0);` `    `  `        ``// sorting the array` `        ``Array.Sort(arr);` `    `  `        ``// sorting queries` `        ``Array.Sort(queries, (q1, q2) => q1.x.CompareTo(q2.x));`   `        ``// current index of array` `        ``int` `curr = 0;`   `        ``// array to hold answer of each Query` `        ``int``[] ans = ``new` `int``[q];`   `        ``// looping through each Query` `        ``for` `(``int` `i = 0; i < q; i++)` `        ``{` `            ``// traversing the array values till it` `            ``// is less than equal to Query number` `            ``while` `(curr < n && arr[curr].val <= queries[i].x)` `            ``{` `                ``// updating the bit array for the array index` `                ``update(bit, arr[curr].idx + 1, 1, n);` `                ``curr++;` `            ``}`   `            ``// Answer for each Query will be number of` `            ``// values less than equal to x upto r minus` `            ``// number of values less than equal to x` `            ``// upto l-1` `            ``ans[queries[i].idx] = query(bit, queries[i].r + 1, n) -` `                            ``query(bit, queries[i].l, n);` `        ``}`   `        ``// printing answer for each Query` `        ``for` `(``int` `i = 0; i < q; i++)` `            ``Console.WriteLine(ans[i]);` `    ``}`   `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``// size of array` `        ``int` `n = 4;` `    `  `        ``// initializing array value and index` `        ``ArrayElement[] arr = ``new` `ArrayElement[n];` `        ``arr[0] = ``new` `ArrayElement(2, 0);` `        ``arr[1] = ``new` `ArrayElement(3, 1);` `        ``arr[2] = ``new` `ArrayElement(4, 2);` `        ``arr[3] = ``new` `ArrayElement(5, 3);`   `        ``// number of queries` `        ``int` `q = 2;` `        ``Query[] queries = ``new` `Query[q];` `        ``queries[0] = ``new` `Query(0, 2, 2, 0);` `        ``queries[1] = ``new` `Query(0, 3, 5, 1);`   `        ``answerQueries(n, queries, q, arr);` `    ``}` `}` `// This code is contributed by prasad264`

## Javascript

 `// JavaScript program to answer queries to count number` `// of elements smaller than or equal to x.`   `// structure to hold queries` `class Query {` `constructor(l, r, x, idx) {` `this``.l = l;` `this``.r = r;` `this``.x = x;` `this``.idx = idx;` `}` `}`   `// structure to hold array` `class ArrayElement {` `constructor(val, idx) {` `this``.val = val;` `this``.idx = idx;` `}`   `// function to compare array elements` `static compare(a, b) {` `return` `a.val - b.val;` `}` `}`   `function` `answerQueries(n, queries, q, arr) {` `// initialising bit array` `let bit = ``new` `Array(n + 1).fill(0);`   `// sorting the array` `arr.sort(ArrayElement.compare);`   `// sorting queries` `queries.sort((q1, q2) => q1.x - q2.x);`   `// current index of array` `let curr = 0;`   `// array to hold answer of each Query` `let ans = ``new` `Array(q).fill(0);`   `// looping through each Query` `for` `(let i = 0; i < q; i++) {` `// traversing the array values till it` `// is less than equal to Query number` `while` `(curr < n && arr[curr].val <= queries[i].x) {` `// updating the bit array for the array index` `update(bit, arr[curr].idx + 1, 1, n);` `curr++;` `}`     `// Answer for each Query will be number of` `// values less than equal to x upto r minus` `// number of values less than equal to x` `// upto l-1` `ans[queries[i].idx] =` `  ``query(bit, queries[i].r + 1, n) - query(bit, queries[i].l, n);` `}`   `// printing answer for each Query` `for` `(let i = 0; i < q; i++) {` `console.log(ans[i]);` `}` `}`   `// bool function to sort queries according to k` `function` `cmp1(q1, q2) {` `return` `q1.x < q2.x;` `}`   `// updating the bit array` `function` `update(bit, idx, val, n) {` `for` `(; idx <= n; idx += idx & -idx) bit[idx] += val;` `}`   `// querying the bit array` `function` `query(bit, idx, n) {` `let sum = 0;` `for` `(; idx > 0; idx -= idx & -idx) sum += bit[idx];` `return` `sum;` `}`   `// size of array` `let n = 4;`   `// initializing array value and index` `let arr = [` `new` `ArrayElement(2, 0),` `new` `ArrayElement(3, 1),` `new` `ArrayElement(4, 2),` `new` `ArrayElement(5, 3),` `];`   `// number of queries` `let q = 2;` `let queries = [` `new` `Query(0, 2, 2, 0),` `new` `Query(0, 3, 5, 1),` `];`   `answerQueries(n, queries, q, arr);`

Output:

```1
4```

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

Auxiliary Space: O(n+q)

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next