![]() |
VOOZH | about |
Given an array of integers arr[], sort the array according to the frequency of elements, i.e. elements that have higher frequency comes first. If the frequencies of two elements are the same, then the smaller number comes first.
Examples:
Input: arr[] = [5, 5, 4, 6, 4]
Output: [4, 4, 5, 5, 6]
Explanation: The highest frequency here is 2. Both 5 and 4 have that frequency. Now since the frequencies are the same the smaller element comes first. So 4 comes first then comes 5. Finally comes 6. The output is 4 4 5 5 6.Input: arr[] = [9, 9, 9, 2, 5]
Output: [9, 9, 9, 2, 5]
Explanation: The highest frequency here is 3. Element 9 has the highest frequency So 9 comes first. Now both 2 and 5 have the same frequency. So we print smaller elements first. The output is 9 9 9 2 5.
Table of Content
The idea is to use sorting to arrange the similar elements together, the count frequencies using linear traversal. Store frequencies and items in a 2d array of elements. Finally sort this 2d array according to the frequency of each element.
Illustration
Input: arr[] = {2 5 2 8 5 6 8 8}
Step1: Sort the array,
After sorting we get: 2 2 5 5 6 8 8 8Step 2: Now construct the 2D array to maintain the count of every element as {freq, element}
{{2, 2}, {2, 5}, {1, 6}, {3, 8}}Step 3: Sort the array by count
{{3, 8}, {2, 2}, {2, 5}, {1, 6}}Set 4: Construct the result array by taking taking the second element and its count as first element
ans[] = {8, 8, 8, 2, 2, 5, 5, 6}
4 4 5 5 6
In the above approach we are firstly sorting the given array to create the frequency array, but instead of doing so, we can use Hash Map or Dictionary. The idea is to store the count of each element in a Hash Map, and then create the frequency array similar to above approach.
4 4 5 5 6
The idea is to store the elements in the form of BST, and if an element in already present then increment the count of the corresponding node. Thereafter store the element and its frequency in a 2d array and sort it based on the frequency. This approach has been discussed in article Sort elements by frequency using BST
The idea is to firstly create the value - frequency table using the Hash Map, then make a Heap such that high frequency remains at top.
Follow the given steps to solve the problem:
Below is the implementation of the above approach:
4 4 5 5 6