 New update is available. Click here to update.
Last Updated: 26 Nov, 2020
##### Frequency In A Sorted Array
Easy
Problem statement #### You are given a sorted array 'ARR' and a number 'X'. Your task is to count the number of occurrences of 'X' in 'ARR'.

##### Note :
``````1. If 'X' is not found in the array, return 0.
2. The given array is sorted in non-decreasing order.
``````
##### Input Format :
``````The first line of input contains an integer ‘T’ representing the number of test cases. Then the test cases follow.

The first line of each test case contains an integer ‘N’ representing the size of the input array.

The second line of each test case contains elements of the array separated by a single space.

The last line of each test case contains a single integer 'X'.
``````
##### Output Format :
``````For each test case, the only line of output will contain a single integer which represents the number of occurrences of target element 'X' in the array.
``````

``````Try to solve it in O(log(N)) time and O(1) space.
``````
##### Note :
``````You don't need to print anything, it has already been taken care of. Just implement the given function.
``````
##### Constraints :
``````1 <= T <= 10^2
1 <= N <= 10^4
0 <= ARR[i], X <= 10^9

Time Limit : 1 sec
`````` Approaches

## 01Approach The basic idea is to first find an occurrence of the target element ‘X’ using binary search. Then, we count the matches toward the left and right sides of the found index.

Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.

The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log(N)).

We basically ignore half of the elements just after one comparison.

Here is the algorithm :

1. Compare ‘X’ with the middle element.
2. If ‘X’ matches with the middle element, we return the ‘MID’ index.
3. Else if ‘X’ is greater than the ‘MID’ element, then ‘X’ can only lie in the right half subarray after the ‘MID’ element. So we recur for the right half.
4. Else ('X' is smaller) recur for the left half. 