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.
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.
Constraints :
1 <= T <= 10^2
1 <= N <= 10^4
0 <= ARR[i], X <= 10^9
Time Limit : 1 sec
The task is to count the number of occurrences of a given number in a sorted array.
Use binary search to find the first and last occurrence of the given number in the array.
Subtract the indices of the ...read more
1. Gave a map based solution asked me to optimize space and time
2. Gave a linear solution with a counter with no extra space
3. Gave a binary search based solution with upper bound and lower bound. The...read more
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: ...read more
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 e...read more
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 coun...read more
Top Amazon Software Developer Intern interview questions & answers
Popular interview questions of Software Developer Intern
Top HR questions asked in Amazon Software Developer Intern
Reviews
Interviews
Salaries
Users/Month