Given an sorted array of positive integers, count number of occurrences for each element in the array. Assume all elements in the array are less than some constant M.
Do this without traversing the complete array. i.e. expected time complexity is less than O(n).
Input: arr = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10] Output: Element 1 occurs 3 times Element 2 occurs 1 times Element 3 occurs 2 times Element 5 occurs 2 times Element 8 occurs 3 times Element 9 occurs 2 times Element 10 occurs 1 times
Method 1 (Linear Search)
The idea is traverse the input array and for each distinct element of array, store its frequency in a map and finally print the map. This approach takes O(n) time.
Method 2 (Use Binary Search)
This problem can be solved in less than O(n) using a modified binary search. The idea is to recursively divide the array into two equal subarrays if its end elements are different. If both its end elements are same, that means that all elements in the subarray is also same as the array is already sorted. We then simply increment the count of the element by size of the subarray.
The time complexity of above approach is O(m log n), where m is number of distinct elements in the array of size n. Since m <= M (a constant), the time complexity of this solution is O(log n).
Below is C++ implementation of above idea –
Element 1 occurs 3 times Element 2 occurs 1 times Element 3 occurs 2 times Element 5 occurs 2 times Element 8 occurs 3 times Element 9 occurs 2 times Element 10 occurs 1 times
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find duplicates in a given array when elements are not limited to a range
- Find even occurring elements in an array of limited range
- Find the missing number in a sorted array of limited range
- Smallest element repeated exactly ‘k’ times (not limited to small range)
- Find the element having different frequency than other array elements
- Find element in a sorted array whose frequency is greater than or equal to n/2.
- Replace each element by the difference of the total size of the array and frequency of that element
- Array range queries for elements with frequency same as value
- Fill an array based on frequency where elements are in range from 0 to n-1
- Remove elements from the array whose frequency lies in the range [l, r]
- Cumulative frequency of count of each element in an unsorted array
- Frequency of each element of an array of small ranged values
- Range Query on array whose each element is XOR of index value and previous element
- Constant time range add operation on an array
- Find the frequency of a number in an array