VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-elements-frequency-set-4-efficient-approach-using-hash/

⇱ Sort elements by frequency | Set 4 (Efficient approach using hash) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort elements by frequency | Set 4 (Efficient approach using hash)

Last Updated : 2 Jun, 2023

Print the elements of an array in the decreasing frequency if 2 numbers have the same frequency then print the one which came first.

Examples: 

Input : arr[] = {2, 5, 2, 8, 5, 6, 8, 8}
Output : arr[] = {8, 8, 8, 2, 2, 5, 5, 6}

Input : arr[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8}
Output : arr[] = {8, 8, 8, 2, 2, 5, 5, 6, -1, 9999999}
 

We have discussed different approaches in below posts : 
Sort elements by frequency | Set 1 
Sort elements by frequency | Set 2 
Sorting Array Elements By Frequency | Set 3 (Using STL)
All of the above approaches work in O(n Log n) time where n is total number of elements. In this post, a new approach is discussed that works in O(n + m Log m) time where n is total number of elements and m is total number of distinct elements.

The idea is to use hashing

  1. We insert all elements and their counts into a hash. This step takes O(n) time where n is number of elements.
  2. We copy the contents of hash to an array (or vector) and sort them by counts. This step takes O(m Log m) time where m is total number of distinct elements.
  3. For maintaining the order of elements if the frequency is the same, we use another hash which has the key as elements of the array and value as the index. If the frequency is the same for two elements then sort elements according to the index.

The below image is a dry run of the above approach:

👁 Image

We do not need to declare another map m2, as it does not provide the proper expected result for the problem.

instead, we need to just check for the first values of the pairs sent as parameters in the sortByVal function.

Below is the implementation of the above approach:


Output
8 8 8 2 2 5 5 -1 6 9999999 

Time Complexity: O(n) + O(m Log m) where n is total number of elements and m is total number of distinct elements
Auxiliary Space: O(n)

This article is contributed by Aarti_Rathi and Ankur Singh and improved by Ankur Goel.  

Simple way to sort by frequency.

The Approach:

  Here In This approach we first we store the element by there frequency in vector_pair format(Using Mapping stl map) then sort it according to frequency then reverse it and apply bubble sort to make the condition true decreasing frequency if 2 numbers have the same frequency then print the one which came first. then print the vector.


Output
8 8 8 2 2 5 5 -1 6 9999999 

Time Complexity: O(n^2) I.e it take O(n) for getting the frequency sorted vector but for sorting in decreasing frequency if 2 numbers have the same frequency then print the one which came first we use bubble sort so it take O(n^2).
Auxiliary Space: O(n),for vector.

Comment