# Queries for counts of array elements with values in given range

Last Updated : 05 Apr, 2023

Given an unsorted array of size n, find no of elements between two elements i and j (both inclusive).

Examples:

```Input :  arr = [1 3 3 9 10 4]
i1 = 1, j1 = 4
i2 = 9, j2 = 12
Output : 4
2
The numbers are: 1 3 3 4 for first query
The numbers are: 9 10 for second query```

Source: Amazon Interview Experience

A simple approach will be to run a for loop to check if each element is in the given range and maintain their count. Time complexity for running each query will be O(n).

Implementation:

## C++

 `// Simple C++ program to count number of elements` `// with values in given range.` `#include ` `using` `namespace` `std;`   `// function to count elements within given range` `int` `countInRange(``int` `arr[], ``int` `n, ``int` `x, ``int` `y)` `{` `    ``// initialize result` `    ``int` `count = 0;` `    ``for` `(``int` `i = 0; i < n; i++) {`   `        ``// check if element is in range` `        ``if` `(arr[i] >= x && arr[i] <= y)` `            ``count++;` `    ``}` `    ``return` `count;` `}`   `// driver function` `int` `main()` `{` `    ``int` `arr[] = { 1, 3, 4, 9, 10, 3 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);`   `    ``// Answer queries` `    ``int` `i = 1, j = 4;` `    ``cout << countInRange(arr, n, i, j) << endl;`   `    ``i = 9, j = 12;` `    ``cout << countInRange(arr, n, i, j) << endl;` `    ``return` `0;` `}`

## Java

 `// Simple java program to count ` `// number of elements with ` `// values in given range.` `import` `java.io.*;`   `class` `GFG ` `{` `    ``// function to count elements within given range` `    ``static` `int` `countInRange(``int` `arr[], ``int` `n, ``int` `x, ``int` `y)` `    ``{` `        ``// initialize result` `        ``int` `count = ``0``;` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `    `  `            ``// check if element is in range` `            ``if` `(arr[i] >= x && arr[i] <= y)` `                ``count++;` `        ``}` `        ``return` `count;` `    ``}`   `    ``// driver function` `    ``public` `static` `void` `main (String[] args)` `    ``{` `        ``int` `arr[] = { ``1``, ``3``, ``4``, ``9``, ``10``, ``3` `};` `        ``int` `n = arr.length;`   `        ``// Answer queries` `        ``int` `i = ``1``, j = ``4``;` `        ``System.out.println ( countInRange(arr, n, i, j)) ;` `    `  `        ``i = ``9``;` `        ``j = ``12``;` `        ``System.out.println ( countInRange(arr, n, i, j)) ;` `        `  `        `  `    ``}` `}`   `// This article is contributed by vt_m`

## Python3

 `# function to count elements within given range` `def` `countInRange(arr, n, x, y):`   `    ``# initialize result` `    ``count ``=` `0``;`   `    ``for` `i ``in` `range``(n):`   `        ``# check if element is in range` `        ``if` `(arr[i] >``=` `x ``and` `arr[i] <``=` `y):` `            ``count ``+``=` `1` `    ``return` `count`   `# driver function` `arr ``=` `[``1``, ``3``, ``4``, ``9``, ``10``, ``3``]` `n ``=` `len``(arr)`   `# Answer queries` `i ``=` `1` `j ``=` `4` `print``(countInRange(arr, n, i, j))` `i ``=` `9` `j ``=` `12` `print``(countInRange(arr, n, i, j))`

## C#

 `// Simple C# program to count ` `// number of elements with ` `// values in given range.` `using` `System;`   `class` `GFG  {` `    `  `    ``// function to count elements` `    ``// within given range` `    ``static` `int` `countInRange(``int` `[]arr, ``int` `n, ` `                            ``int` `x, ``int` `y)` `    ``{` `        `  `        ``// initialize result` `        ``int` `count = 0;` `        ``for` `(``int` `i = 0; i < n; i++) {` `    `  `            ``// check if element is in range` `            ``if` `(arr[i] >= x && arr[i] <= y)` `                ``count++;` `        ``}` `        ``return` `count;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `Main ()` `    ``{` `        ``int``[]arr = {1, 3, 4, 9, 10, 3};` `        ``int` `n = arr.Length;`   `        ``// Answer queries` `        ``int` `i = 1, j = 4;` `        ``Console.WriteLine( countInRange(arr, n, i, j)) ;` `    `  `        ``i = 9;` `        ``j = 12;` `        ``Console.WriteLine( countInRange(arr, n, i, j)) ;` `        `  `        `  `    ``}` `}`   `// This code is contributed by vt_m.`

## PHP

 `= ``\$x` `&& ` `            ``\$arr``[``\$i``] <= ``\$y``)` `            ``\$count``++;` `    ``}` `    ``return` `\$count``;` `}`   `    ``// Driver Code` `    ``\$arr` `= ``array``(1, 3, 4, 9, 10, 3);` `    ``\$n` `= ``count``(``\$arr``);`   `    ``// Answer queries` `    ``\$i` `= 1;` `    ``\$j` `= 4;` `    ``echo` `countInRange(``\$arr``, ``\$n``, ``\$i``, ``\$j``).``"\n"``;`   `    ``\$i` `= 9;` `    ``\$j` `= 12;` `    ``echo` `countInRange(``\$arr``, ``\$n``, ``\$i``, ``\$j``).``"\n"``;` `    `  `// This code is contributed by Sam007` `?>`

## Javascript

 ``

Output

```4
2```

Time Complexity: O(n),
Auxiliary Space: O(1)

Segment Tree approach :

The segment tree is a binary tree where each node represents a segment of the array. The leaves of the tree represent the individual elements of the array, and the parent nodes represent the union of their children.

• To answer a query [i, j], we traverse the segment tree from the root to the leaves, keeping track of the segments that contain i and j. At each node, we use the precomputed values to compute the number of elements in the segment that are less than or equal to x. We merge the values for the left and right child nodes and return the final result.

Implementation :

## C++

 `// C++ program to count number of elements` `// with values in given range using segment tree`   `#include ` `using` `namespace` `std;`   `// Segment Tree class` `class` `SegmentTree {` `public``:` `    ``SegmentTree(``int` `n) { tree.resize(4 * n); }`   `    ``// build the tree with array elements` `    ``void` `build(``int` `arr[], ``int` `v, ``int` `tl, ``int` `tr)` `    ``{` `        ``if` `(tl == tr) {` `            ``tree[v] = (arr[tl] >= low && arr[tl] <= high)` `                          ``? 1` `                          ``: 0;` `        ``}` `        ``else` `{` `            ``int` `tm` `= (tl + tr) / 2;` `            ``build(arr, v * 2, tl, ``tm``);` `            ``build(arr, v * 2 + 1, ``tm` `+ 1, tr);` `            ``tree[v] = tree[v * 2] + tree[v * 2 + 1];` `        ``}` `    ``}`   `    ``// query the tree for given range` `    ``int` `query(``int` `v, ``int` `tl, ``int` `tr, ``int` `l, ``int` `r)` `    ``{` `        ``if` `(l > r) {` `            ``return` `0;` `        ``}` `        ``if` `(l == tl && r == tr) {` `            ``return` `tree[v];` `        ``}` `        ``int` `tm` `= (tl + tr) / 2;` `        ``return` `query(v * 2, tl, ``tm``, l, min(r, ``tm``))` `               ``+ query(v * 2 + 1, ``tm` `+ 1, tr,` `                       ``max(l, ``tm` `+ 1), r);` `    ``}`   `    ``// update tree at index i with given value` `    ``void` `update(``int` `v, ``int` `tl, ``int` `tr, ``int` `i, ``int` `val)` `    ``{` `        ``if` `(tl == tr) {` `            ``tree[v] = (val >= low && val <= high) ? 1 : 0;` `        ``}` `        ``else` `{` `            ``int` `tm` `= (tl + tr) / 2;` `            ``if` `(i <= ``tm``) {` `                ``update(v * 2, tl, ``tm``, i, val);` `            ``}` `            ``else` `{` `                ``update(v * 2 + 1, ``tm` `+ 1, tr, i, val);` `            ``}` `            ``tree[v] = tree[v * 2] + tree[v * 2 + 1];` `        ``}` `    ``}`   `    ``// set range for the tree` `    ``void` `setRange(``int` `l, ``int` `h)` `    ``{` `        ``low = l;` `        ``high = h;` `    ``}`   `private``:` `    ``vector<``int``> tree;` `    ``int` `low, high;` `};`   `// function to count elements within given range` `int` `countInRange(``int` `arr[], ``int` `n, ``int` `x, ``int` `y)` `{` `    ``SegmentTree st(n);` `    ``st.setRange(x, y);` `    ``st.build(arr, 1, 0, n - 1);` `    ``return` `st.query(1, 0, n - 1, 0, n - 1);` `}`   `// driver function` `int` `main()` `{` `    ``int` `arr[] = { 1, 3, 4, 9, 10, 3 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);`   `    ``// Answer queries` `    ``int` `i = 1, j = 4;` `    ``cout << countInRange(arr, n, i, j) << endl;`   `    ``i = 9, j = 12;` `    ``cout << countInRange(arr, n, i, j) << endl;` `    ``return` `0;` `}`   `// this code is contributed by bhardwajji`

## Java

 `import` `java.util.*;`   `class` `SegmentTree {` `    ``private` `List tree;` `    ``private` `int` `low, high;`   `    ``SegmentTree(``int` `n)` `    ``{` `        ``tree = ``new` `ArrayList<>(``4` `* n);` `        ``for` `(``int` `i = ``0``; i < ``4` `* n; i++) {` `            ``tree.add(``0``);` `        ``}` `    ``}`   `    ``// build the tree with array elements` `    ``void` `build(``int``[] arr, ``int` `v, ``int` `tl, ``int` `tr)` `    ``{` `        ``if` `(tl == tr) {` `            ``tree.set(v, (arr[tl] >= low && arr[tl] <= high)` `                            ``? ``1` `                            ``: ``0``);` `        ``}` `        ``else` `{` `            ``int` `tm = (tl + tr) / ``2``;` `            ``build(arr, v * ``2``, tl, tm);` `            ``build(arr, v * ``2` `+ ``1``, tm + ``1``, tr);` `            ``tree.set(v,` `                     ``tree.get(v * ``2``) + tree.get(v * ``2` `+ ``1``));` `        ``}` `    ``}`   `    ``// query the tree for given range` `    ``int` `query(``int` `v, ``int` `tl, ``int` `tr, ``int` `l, ``int` `r)` `    ``{` `        ``if` `(l > r) {` `            ``return` `0``;` `        ``}` `        ``if` `(l == tl && r == tr) {` `            ``return` `tree.get(v);` `        ``}` `        ``int` `tm = (tl + tr) / ``2``;` `        ``return` `query(v * ``2``, tl, tm, l, Math.min(r, tm))` `            ``+ query(v * ``2` `+ ``1``, tm + ``1``, tr,` `                    ``Math.max(l, tm + ``1``), r);` `    ``}`   `    ``// update tree at index i with given value` `    ``void` `update(``int` `v, ``int` `tl, ``int` `tr, ``int` `i, ``int` `val)` `    ``{` `        ``if` `(tl == tr) {` `            ``tree.set(v,` `                     ``(val >= low && val <= high) ? ``1` `: ``0``);` `        ``}` `        ``else` `{` `            ``int` `tm = (tl + tr) / ``2``;` `            ``if` `(i <= tm) {` `                ``update(v * ``2``, tl, tm, i, val);` `            ``}` `            ``else` `{` `                ``update(v * ``2` `+ ``1``, tm + ``1``, tr, i, val);` `            ``}` `            ``tree.set(v,` `                     ``tree.get(v * ``2``) + tree.get(v * ``2` `+ ``1``));` `        ``}` `    ``}`   `    ``// set range for the tree` `    ``void` `setRange(``int` `l, ``int` `h)` `    ``{` `        ``low = l;` `        ``high = h;` `    ``}` `}`   `public` `class` `GFG {` `    ``// function to count elements within given range` `    ``static` `int` `countInRange(``int``[] arr, ``int` `n, ``int` `x, ``int` `y)` `    ``{` `        ``SegmentTree st = ``new` `SegmentTree(n);` `        ``st.setRange(x, y);` `        ``st.build(arr, ``1``, ``0``, n - ``1``);` `        ``return` `st.query(``1``, ``0``, n - ``1``, ``0``, n - ``1``);` `    ``}`   `    ``// driver function` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int``[] arr = { ``1``, ``3``, ``4``, ``9``, ``10``, ``3` `};` `        ``int` `n = arr.length;`   `        ``// Answer queries` `        ``int` `i = ``1``, j = ``4``;` `        ``System.out.println(countInRange(arr, n, i, j));`   `        ``i = ``9``;` `        ``j = ``12``;` `        ``System.out.println(countInRange(arr, n, i, j));` `    ``}` `}`

## Python

 `# Python program to count number of elements` `# with values in given range using segment tree`   `# Segment Tree class`     `class` `SegmentTree:` `    ``def` `__init__(``self``, n):` `        ``self``.tree ``=` `[``0``] ``*` `(``4``*``n)`   `    ``# build the tree with array elements` `    ``def` `build(``self``, arr, v, tl, tr, low, high):` `        ``if` `tl ``=``=` `tr:` `            ``self``.tree[v] ``=` `1` `if` `low <``=` `arr[tl] <``=` `high ``else` `0` `        ``else``:` `            ``tm ``=` `(tl ``+` `tr) ``/``/` `2` `            ``self``.build(arr, v``*``2``, tl, tm, low, high)` `            ``self``.build(arr, v``*``2``+``1``, tm``+``1``, tr, low, high)` `            ``self``.tree[v] ``=` `self``.tree[v``*``2``] ``+` `self``.tree[v``*``2``+``1``]`   `    ``# query the tree for given range` `    ``def` `query(``self``, v, tl, tr, l, r):` `        ``if` `l > r:` `            ``return` `0` `        ``if` `l ``=``=` `tl ``and` `r ``=``=` `tr:` `            ``return` `self``.tree[v]` `        ``tm ``=` `(tl ``+` `tr) ``/``/` `2` `        ``return` `self``.query(v``*``2``, tl, tm, l, ``min``(r, tm)) ``+` `\` `            ``self``.query(v``*``2``+``1``, tm``+``1``, tr, ``max``(l, tm``+``1``), r)`   `    ``# update tree at index i with given value` `    ``def` `update(``self``, v, tl, tr, i, val, low, high):` `        ``if` `tl ``=``=` `tr:` `            ``self``.tree[v] ``=` `1` `if` `low <``=` `val <``=` `high ``else` `0` `        ``else``:` `            ``tm ``=` `(tl ``+` `tr) ``/``/` `2` `            ``if` `i <``=` `tm:` `                ``self``.update(v``*``2``, tl, tm, i, val, low, high)` `            ``else``:` `                ``self``.update(v``*``2``+``1``, tm``+``1``, tr, i, val, low, high)` `            ``self``.tree[v] ``=` `self``.tree[v``*``2``] ``+` `self``.tree[v``*``2``+``1``]`   `    ``# set range for the tree` `    ``def` `set_range(``self``, low, high):` `        ``self``.low ``=` `low` `        ``self``.high ``=` `high`   `# function to count elements within given range`     `def` `count_in_range(arr, n, x, y):` `    ``st ``=` `SegmentTree(n)` `    ``st.set_range(x, y)` `    ``st.build(arr, ``1``, ``0``, n``-``1``, x, y)` `    ``return` `st.query(``1``, ``0``, n``-``1``, ``0``, n``-``1``)`     `# driver function` `if` `__name__ ``=``=` `'__main__'``:` `    ``arr ``=` `[``1``, ``3``, ``4``, ``9``, ``10``, ``3``]` `    ``n ``=` `len``(arr)`   `    ``# Answer queries` `    ``i, j ``=` `1``, ``4` `    ``print``(count_in_range(arr, n, i, j))`   `    ``i, j ``=` `9``, ``12` `    ``print``(count_in_range(arr, n, i, j))`

## C#

 `using` `System;`   `public` `class` `SegmentTree {` `    ``private` `int``[] tree;` `    ``private` `int` `low, high;`   `    ``public` `SegmentTree(``int` `n) { tree = ``new` `int``[4 * n]; }`   `    ``public` `void` `Build(``int``[] arr, ``int` `v, ``int` `tl, ``int` `tr)` `    ``{` `        ``if` `(tl == tr) {` `            ``tree[v] = (arr[tl] >= low && arr[tl] <= high)` `                          ``? 1` `                          ``: 0;` `        ``}` `        ``else` `{` `            ``int` `tm = (tl + tr) / 2;` `            ``Build(arr, v * 2, tl, tm);` `            ``Build(arr, v * 2 + 1, tm + 1, tr);` `            ``tree[v] = tree[v * 2] + tree[v * 2 + 1];` `        ``}` `    ``}`   `    ``public` `int` `Query(``int` `v, ``int` `tl, ``int` `tr, ``int` `l, ``int` `r)` `    ``{` `        ``if` `(l > r) {` `            ``return` `0;` `        ``}` `        ``if` `(l == tl && r == tr) {` `            ``return` `tree[v];` `        ``}` `        ``int` `tm = (tl + tr) / 2;` `        ``return` `Query(v * 2, tl, tm, l, Math.Min(r, tm))` `            ``+ Query(v * 2 + 1, tm + 1, tr,` `                    ``Math.Max(l, tm + 1), r);` `    ``}`   `    ``public` `void` `Update(``int` `v, ``int` `tl, ``int` `tr, ``int` `i,` `                       ``int` `val)` `    ``{` `        ``if` `(tl == tr) {` `            ``tree[v] = (val >= low && val <= high) ? 1 : 0;` `        ``}` `        ``else` `{` `            ``int` `tm = (tl + tr) / 2;` `            ``if` `(i <= tm) {` `                ``Update(v * 2, tl, tm, i, val);` `            ``}` `            ``else` `{` `                ``Update(v * 2 + 1, tm + 1, tr, i, val);` `            ``}` `            ``tree[v] = tree[v * 2] + tree[v * 2 + 1];` `        ``}` `    ``}`   `    ``public` `void` `SetRange(``int` `l, ``int` `h)` `    ``{` `        ``low = l;` `        ``high = h;` `    ``}` `}`   `public` `class` `Program {` `    ``public` `static` `int` `CountInRange(``int``[] arr, ``int` `n, ``int` `x,` `                                   ``int` `y)` `    ``{` `        ``SegmentTree st = ``new` `SegmentTree(n);` `        ``st.SetRange(x, y);` `        ``st.Build(arr, 1, 0, n - 1);` `        ``return` `st.Query(1, 0, n - 1, 0, n - 1);` `    ``}`   `    ``public` `static` `void` `Main()` `    ``{` `        ``int``[] arr = { 1, 3, 4, 9, 10, 3 };` `        ``int` `n = arr.Length;`   `        ``// Answer queries` `        ``int` `i = 1, j = 4;` `        ``Console.WriteLine(CountInRange(arr, n, i, j));`   `        ``i = 9;` `        ``j = 12;` `        ``Console.WriteLine(CountInRange(arr, n, i, j));` `    ``}` `}`

## Javascript

 `class SegmentTree {` `    ``constructor(n) {` `        ``this``.tree = ``new` `Array(4 * n).fill(0);` `        ``this``.low = 0;` `        ``this``.high = 0;` `    ``}`   `    ``// build the tree with array elements` `    ``build(arr, v, tl, tr) {` `        ``if` `(tl === tr) {` `            ``this``.tree[v] = (arr[tl] >= ``this``.low && arr[tl] <= ``this``.high) ? 1 : 0;` `        ``} ``else` `{` `            ``const tm = Math.floor((tl + tr) / 2);` `            ``this``.build(arr, v * 2, tl, tm);` `            ``this``.build(arr, v * 2 + 1, tm + 1, tr);` `            ``this``.tree[v] = ``this``.tree[v * 2] + ``this``.tree[v * 2 + 1];` `        ``}` `    ``}`   `    ``// query the tree for given range` `    ``query(v, tl, tr, l, r) {` `        ``if` `(l > r) {` `            ``return` `0;` `        ``}` `        ``if` `(l === tl && r === tr) {` `            ``return` `this``.tree[v];` `        ``}` `        ``const tm = Math.floor((tl + tr) / 2);` `        ``return` `this``.query(v * 2, tl, tm, l, Math.min(r, tm))` `            ``+ ``this``.query(v * 2 + 1, tm + 1, tr, Math.max(l, tm + 1), r);` `    ``}`   `    ``// update tree at index i with given value` `    ``update(v, tl, tr, i, val) {` `        ``if` `(tl === tr) {` `            ``this``.tree[v] = (val >= ``this``.low && val <= ``this``.high) ? 1 : 0;` `        ``} ``else` `{` `            ``const tm = Math.floor((tl + tr) / 2);` `            ``if` `(i <= tm) {` `                ``this``.update(v * 2, tl, tm, i, val);` `            ``} ``else` `{` `                ``this``.update(v * 2 + 1, tm + 1, tr, i, val);` `            ``}` `            ``this``.tree[v] = ``this``.tree[v * 2] + ``this``.tree[v * 2 + 1];` `        ``}` `    ``}`   `    ``// set range for the tree` `    ``setRange(l, h) {` `        ``this``.low = l;` `        ``this``.high = h;` `    ``}` `}`   `// function to count elements within given range` `function` `countInRange(arr, n, x, y) {` `    ``const st = ``new` `SegmentTree(n);` `    ``st.setRange(x, y);` `    ``st.build(arr, 1, 0, n - 1);` `    ``return` `st.query(1, 0, n - 1, 0, n - 1);` `}`   `// driver function` `function` `main() {` `    ``const arr = [1, 3, 4, 9, 10, 3];` `    ``const n = arr.length;`   `    ``// Answer queries` `    ``let i = 1, j = 4;` `    ``console.log(countInRange(arr, n, i, j));`   `    ``i = 9;` `    ``j = 12;` `    ``console.log(countInRange(arr, n, i, j));` `}`   `main();`

Output

```4
2```

Time Complexity: O(n log n)
Auxiliary Space: O(n)

An Efficient Approach will be to first sort the array and then using a modified binary search function find two indices, one of first element greater than or equal to lower bound of range and the other of the last element less than or equal to upperbound. Time for running each query will be O(logn) and for sorting the array once will be O(nlogn).

Implementation:

## C++

 `// Efficient C++ program to count number of elements` `// with values in given range.` `#include ` `using` `namespace` `std;`   `// function to find first index >= x` `int` `lowerIndex(``int` `arr[], ``int` `n, ``int` `x)` `{` `    ``int` `l = 0, h = n - 1;` `    ``while` `(l <= h) {` `        ``int` `mid = (l + h) / 2;` `        ``if` `(arr[mid] >= x)` `            ``h = mid - 1;` `        ``else` `            ``l = mid + 1;` `    ``}` `    ``return` `l;` `}`   `// function to find last index <= y` `int` `upperIndex(``int` `arr[], ``int` `n, ``int` `y)` `{` `    ``int` `l = 0, h = n - 1;` `    ``while` `(l <= h) {` `        ``int` `mid = (l + h) / 2;` `        ``if` `(arr[mid] <= y)` `            ``l = mid + 1;` `        ``else` `            ``h = mid - 1;` `    ``}` `    ``return` `h;` `}`   `// function to count elements within given range` `int` `countInRange(``int` `arr[], ``int` `n, ``int` `x, ``int` `y)` `{` `    ``// initialize result` `    ``int` `count = 0;` `    ``count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1;` `    ``return` `count;` `}`   `// driver function` `int` `main()` `{` `    ``int` `arr[] = { 1, 4, 4, 9, 10, 3 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);`   `    ``// Preprocess array` `    ``sort(arr, arr + n);`   `    ``// Answer queries` `    ``int` `i = 1, j = 4;` `    ``cout << countInRange(arr, n, i, j) << endl;`   `    ``i = 9, j = 12;` `    ``cout << countInRange(arr, n, i, j) << endl;` `    ``return` `0;` `}`

## Java

 `// Efficient C++ program to count number ` `// of elements with values in given range.` `import` `java.io.*;` `import` `java.util.Arrays;`   `class` `GFG ` `{` `    ``// function to find first index >= x` `    ``static` `int` `lowerIndex(``int` `arr[], ``int` `n, ``int` `x)` `    ``{` `        ``int` `l = ``0``, h = n - ``1``;` `        ``while` `(l <= h) ` `        ``{` `            ``int` `mid = (l + h) / ``2``;` `            ``if` `(arr[mid] >= x)` `                ``h = mid - ``1``;` `            ``else` `                ``l = mid + ``1``;` `        ``}` `        ``return` `l;` `    ``}` `    `  `    ``// function to find last index <= y` `    ``static` `int` `upperIndex(``int` `arr[], ``int` `n, ``int` `y)` `    ``{` `        ``int` `l = ``0``, h = n - ``1``;` `        ``while` `(l <= h) ` `        ``{` `            ``int` `mid = (l + h) / ``2``;` `            ``if` `(arr[mid] <= y)` `                ``l = mid + ``1``;` `            ``else` `                ``h = mid - ``1``;` `        ``}` `        ``return` `h;` `    ``}` `    `  `    ``// function to count elements within given range` `    ``static` `int` `countInRange(``int` `arr[], ``int` `n, ``int` `x, ``int` `y)` `    ``{` `        ``// initialize result` `        ``int` `count = ``0``;` `        ``count = upperIndex(arr, n, y) - ` `                ``lowerIndex(arr, n, x) + ``1``;` `        ``return` `count;` `    ``}` `    `  `    ``// Driver function` `    ``public` `static` `void` `main (String[] args) ` `    ``{` `        ``int` `arr[] = { ``1``, ``4``, ``4``, ``9``, ``10``, ``3` `};` `        ``int` `n = arr.length;` `    `  `        ``// Preprocess array` `        ``Arrays.sort(arr);` `    `  `        ``// Answer queries` `        ``int` `i = ``1``, j = ``4``;` `        ``System.out.println( countInRange(arr, n, i, j)); ;` `    `  `        ``i = ``9``;` `        ``j = ``12``;` `        ``System.out.println( countInRange(arr, n, i, j));` `    `    `    ``}` `}`   `// `

## Python3

 `# function to find first index >= x` `def` `lowerIndex(arr, n, x):` `  ``l ``=` `0` `  ``h ``=` `n``-``1` `  ``while` `(l <``=` `h):` `    ``mid ``=` `int``((l ``+` `h)``/``/``2``)` `    ``if` `(arr[mid] >``=` `x):` `      ``h ``=` `mid ``-` `1` `    ``else``:` `      ``l ``=` `mid ``+` `1` `  ``return` `l`     `# function to find last index <= x` `def` `upperIndex(arr, n, x):` `  ``l ``=` `0` `  ``h ``=` `n``-``1` `  ``while` `(l <``=` `h):` `    ``mid ``=` `int``((l ``+` `h)``/``/``2``)` `    ``if` `(arr[mid] <``=` `x):` `      ``l ``=` `mid ``+` `1` `    ``else``:` `      ``h ``=` `mid ``-` `1` `  ``return` `h`     `# function to count elements within given range` `def` `countInRange(arr, n, x, y):` `  ``# initialize result` `  ``count ``=` `0``;` `  ``count ``=` `upperIndex(arr, n, y) ``-` `lowerIndex(arr, n, x) ``+` `1``;` `  ``return` `count`   `# driver function` `arr ``=` `[``1``, ``3``, ``4``, ``9``, ``10``, ``3``]`   `# Preprocess array` `arr.sort()` `n ``=` `len``(arr)`   `# Answer queries` `i ``=` `1` `j ``=` `4` `print``(countInRange(arr, n, i, j))` `i ``=` `9` `j ``=` `12` `print``(countInRange(arr, n, i, j))`

## C#

 `// Efficient C# program to count number ` `// of elements with values in given range.` `using` `System;`   `class` `GFG ` `{` `    `  `    ``// function to find first index >= x` `    ``static` `int` `lowerIndex(``int` `[]arr, ``int` `n,` `                          ``int` `x)` `    ``{` `        `  `        ``int` `l = 0, h = n - 1;` `        ``while` `(l <= h) ` `        ``{` `            ``int` `mid = (l + h) / 2;` `            ``if` `(arr[mid] >= x)` `                ``h = mid - 1;` `            ``else` `                ``l = mid + 1;` `        ``}` `        ``return` `l;` `    ``}` `    `  `    ``// function to find last index <= y` `    ``static` `int` `upperIndex(``int` `[]arr, ``int` `n,` `                          ``int` `y)` `    ``{` `        ``int` `l = 0, h = n - 1;` `        ``while` `(l <= h) ` `        ``{` `            ``int` `mid = (l + h) / 2;` `            ``if` `(arr[mid] <= y)` `                ``l = mid + 1;` `            ``else` `                ``h = mid - 1;` `        ``}` `        ``return` `h;` `    ``}` `    `  `    ``// function to count elements ` `    ``// within given range` `    ``static` `int` `countInRange(``int` `[]arr, ``int` `n, ` `                            ``int` `x, ``int` `y)` `    ``{` `        `  `        ``// initialize result` `        ``int` `count = 0;` `        ``count = upperIndex(arr, n, y) - ` `                ``lowerIndex(arr, n, x) + 1;` `        ``return` `count;` `    ``}` `    `  `    ``// Driver code` `    ``public` `static` `void` `Main () ` `    ``{` `        ``int` `[]arr = {1, 4, 4, 9, 10, 3};` `        ``int` `n = arr.Length;` `    `  `        ``// Preprocess array` `        ``Array.Sort(arr);` `    `  `        ``// Answer queries` `        ``int` `i = 1, j = 4;` `        ``Console.WriteLine(countInRange(arr, n, i, j)); ;` `    `  `        ``i = 9;` `        ``j = 12;` `        ``Console.WriteLine(countInRange(arr, n, i, j));` `    `    `    ``}` `}`   `// This code is contributed by vt_m.`

## PHP

 `= x ` `function` `lowerIndex(``\$arr``, ``\$n``, ``\$x``) ` `{ ` `    ``\$l` `= 0; ``\$h` `= ``\$n` `- 1; ` `    ``while` `(``\$l` `<= ``\$h``)` `    ``{ ` `        ``\$mid` `= (``\$l` `+ ``\$h``) / 2; ` `        ``if` `(``\$arr``[``\$mid``] >= ``\$x``) ` `            ``\$h` `= ``\$mid` `- 1; ` `        ``else` `            ``\$l` `= ``\$mid` `+ 1; ` `    ``} ` `    ``return` `\$l``; ` `} `   `// function to find last index <= y ` `function` `upperIndex(``\$arr``, ``\$n``, ``\$y``) ` `{ ` `    ``\$l` `= 0; ``\$h` `= ``\$n` `- 1; ` `    ``while` `(``\$l` `<= ``\$h``) ` `    ``{ ` `        ``\$mid` `= (``\$l` `+ ``\$h``) / 2; ` `        ``if` `(``\$arr``[``\$mid``] <= ``\$y``) ` `            ``\$l` `= ``\$mid` `+ 1; ` `        ``else` `            ``\$h` `= ``\$mid` `- 1; ` `    ``} ` `    ``return` `\$h``; ` `} `   `// function to count elements ` `// within given range ` `function` `countInRange(``\$arr``, ``\$n``, ``\$x``, ``\$y``) ` `{ ` `    ``// initialize result ` `    ``\$count` `= 0; ` `    ``\$count` `= (upperIndex(``\$arr``, ``\$n``, ``\$y``) - ` `              ``lowerIndex(``\$arr``, ``\$n``, ``\$x``) + 1);` `    ``\$t` `= ``floor``(``\$count``);` `    ``return` `\$t``; ` `} `   `// Driver Code`   `\$arr` `= ``array``( 1, 4, 4, 9, 10, 3 ); ` `\$n` `= sizeof(``\$arr``); `   `// Preprocess array ` `sort(``\$arr``); `   `// Answer queries ` `\$i` `= 1; ``\$j` `= 4; ` `echo` `countInRange(``\$arr``, ``\$n``, ``\$i``, ``\$j``), ``"\n"``; `   `\$i` `= 9; ``\$j` `= 12; ` `echo` `countInRange(``\$arr``, ``\$n``, ``\$i``, ``\$j``), ``"\n"``; `   `// This code is contributed by Sachin` `?>`

## Javascript

 ``

Output

```4
2```

Time Complexity: O(n log n),
Auxiliary Space: O(1)