![]() |
VOOZH | about |
Given an array arr[] of non-negative integers which may contain duplicate elements. Return the frequency of each distinct element present in the array.
Examples:
Input: arr[] = [10, 20, 10, 5, 20]
Output: [[5, 1], [10, 2], [20, 2]]
Explanation: Here 5 occurs once, 10 occurs 2 times and 20 occurs 2 times.Input: arr[] = [10, 20, 20]
Output: [[10, 1], [20, 2]]
Explanation: Here 10 occurs 1 time, 20 occurs 2 times.
Table of Content
A simple solution is to run two loops. For every item count number of times, it occurs. To avoid duplicate printing, keep track of processed items.
5 1 10 2 20 2
We can find frequency of array elements using Binary search function . First we will sort the array for binary search . Our frequency of element will be '(last occ - first occ) + 1' of a element in a array.
5 1 10 2 20 2
Time Complexity: O(n × log2n) , where O(log2n) time for binary search function.
Auxiliary Space: O(1), as using constant extra space
An efficient solution is using a hash map (e.g. unordered_map in C++, HashMap in Java, dict in Python, or Dictionary in C#), we can store elements as keys and their frequencies as values.
5 1 10 2 20 2