Interview Prep | Blog | Scoring | Environment | FAQ | About Us | Support | Careers | Terms Of Service | Privacy Policy | Request a Feature
Sort the array elements based on its frequencies Assumptions - 1. Sort the array based on its natural occurrence in an ascending order 2. If two numbers having same frequencies then sort them based on natural number precedence Example: - [ 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5] Solution: - Output:-
Print the elements of an array in the decreasing frequency if 2 numbers have 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}METHOD 1 (Use Sorting)
Example: Input 2 5 2 8 5 6 8 8 After sorting we get 2 2 5 5 6 8 8 8 Now construct the 2D array as 2, 2 5, 2 6, 1 8, 3 Sort by count 8, 3 2, 2 5, 2 6, 1How to maintain the order of elements if the frequency is the same? The above approach doesn’t make sure the order of elements if the frequency is same. To handle this, we should use indexes in step 3, if two counts are same then we should first process(or print) the element with a lower index. In step 1, we should store the indexes instead of elements. Input 2 5 2 8 5 6 8 8 After sorting we get Element 2 2 5 5 6 8 8 8 Index 0 2 1 4 5 3 6 7 Now construct the 2D array as Index, Count 0, 2 1, 2 5, 1 3, 3 Sort by count (consider indexes in case of tie) 3, 3 0, 2 1, 2 5, 1 Print the elements using indexes in the above 2D array.Below is the implementation of above approach –
Output: 8 8 8 2 2 5 5 6 -1 9999999Thanks to Gaurav Ahirwar for providing above implementation. METHOD 2 (Use Hashing and Sorting) Using a hashing mechanism, we can store the elements (also first index) and their counts in a hash. Finally, sort the hash elements according to their counts. Below is the implementation of above approach –
Output: 8 8 8 2 2 5 5 6 -1 9999999This can also be solved by Using two maps, one for array element as an index and after this second map whose keys are frequency and value are array elements. METHOD 3(Use BST and Sorting)
Time Complexity: O(nlogn) if a Self Balancing Binary Search Tree is used. This is implemented in Set 2. https://youtu.be/NBXf9vCksuM Set 2: Sort elements by frequency | Set 2 Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Article Tags : Practice Tags : |