Problem of the day
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.
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.
Follow Up :
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.
1 <= T <= 10^2
1 <= N <= 10^4
0 <= ARR[i], X <= 10^9
Time Limit : 1 sec
2
7
1 1 2 2 2 2 3
2
5
1 2 2 3 3
4
4
0
For the first test case, the target element 2 occurs four times in the array at indexes from 2 to 5.
For the second test case, the target element 4 doesn’t occur in the array.
2
4
2 3 4 4
4
6
5 7 7 8 8 10
10
2
1
Use binary search to find the target element ‘X’ in the array.
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 :
O(N), where ‘N’ is the size of the given array.
Time complexities of the functions we have used:
Hence, the overall time complexity is O(N + log(N)) i.e. O(N).
O(log(N)), where ‘N’ is the size of the given array.
Recursive stack will be called maximum of log(N) times as we are repeatedly dividing the array into half parts. Hence, the overall space complexity will be O(log(N)).