![]() |
VOOZH | about |
Given a sorted array arr[] and an integer target, find the number of occurrences of target in given array.
Examples:
Input: arr[] = [1, 1, 2, 2, 2, 2, 3], target = 2
Output: 4
Explanation: 2 occurs 4 times in the given array.Input: arr[] = [1, 1, 2, 2, 2, 2, 3], target = 4
Output: 0
Explanation: 4 is not present in the given array.
Table of Content
The idea is to traverse the array and for each element, check if it is equal to the target. If you find any element equal to target increment the value of counter variable.
4
Since the array is already sorted, we can use binary search to find the occurrences of a given target. First, we find the index of the first occurrence (Lower Bound) of target and then the index of the first element greater than the target (Upper Bound). The difference between these two indices will give the total number of occurrences of the target.
4