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'.
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.
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
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 :
Linearly search for target element βXβ, count the occurrences of βXβ and return the βCOUNTβ.
Linear search is a method for finding an element within a list/array. It sequentially checks each element of the list until a match is found or the whole list/array has been searched.
The basic idea is to first find the first and the last occurrence of the target element βXβ using binary search. Then, return the difference of these indexes +1, as this the count of all the occurrences of the target element βXβ in the array.
Here is the algorithm :
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 :
Search In A Sorted 2D Matrix
Ninja And The Strictly Increasing Array
Negative To The End
Day 28 : Fake Coin Problem
Day 28 : Fake Coin Problem
Find Duplicate in Array