Given an unsorted array of integers which may contain repeated elements, sort the elements in descending order of some of its occurrence. If there exists more than one element whose sum of occurrences are the same then, the one which is greater will come first.
Examples:
Input: arr[] = [2, 4, 1, 2, 4, 2, 10]
Output: arr[] = [10, 4, 4, 2, 2, 2, 1]
Explanation:
Here, 2 appears 3 times, 4 appears 2 times, 1 appears 1 time and 10 appears 1 time.
Thus,
Sum of all occurrences of 2 in given array = 2 * 3 = 6,
Sum of all occurrences of 4 = 4 * 2 = 8,
Sum of all occurrences of 10 = 10 * 1 = 10,
Sum of all occurrences of 1 = 1 * 1 = 1.
Therefore sorting the array in descending order based on the above sum = [ 10, 4, 4, 2, 2, 2, 1 ]
Input2: arr[] = [2, 3, 2, 3, 2, 1, 1, 9, 6, 9, 1, 2]
Output2: [9, 9, 2, 2, 2, 2, 6, 3, 3, 1, 1, 1]
Approach:
- Create a map that will map elements to it appearance ie if a occur one time then a will map to a but if a occur m times then a will be map to a*m.
- After doing the mapping sort the dictionary in descending order based on their values not keys. In case of tie, sort based on values.
- Finally copy the sorted dictionary keys in the final output array and there frequency is obtain based on their key-value pairs i.e. if a is mapped to a*m it means we need to include a, m times in output array.
Below is the implementation of the above approach:
C++
// c++ code for the above approach #include <iostream> #include <vector> #include <unordered_map> #include <algorithm> using namespace std; vector< int > sort_desc(vector< int >& arr) { unordered_map< int , int > d_sum, d_count; for ( auto x : arr) { if (d_sum.find(x) == d_sum.end()) { d_sum[x] = x; d_count[x] = 1; } else { d_sum[x] += x; d_count[x] += 1; } } vector<pair< int , int >> l; for ( auto & x : d_sum) { l.push_back({ x.second, x.first }); } sort(l.rbegin(), l.rend()); vector< int > ans; for ( auto & x : l) { ans.insert(ans.end(), d_count[x.second], x.second); } return ans; } int main() { vector< int > arr{ 3, 5, 2, 2, 3, 1, 3, 1 }; // Function Call vector< int > sorted_arr = sort_desc(arr); for ( auto x : sorted_arr) { cout << x << " " ; } return 0; } // This code is contributed by princekumaras |
Python
# Python3 program to sort elements of # arr[] in descending order of sum # of its occurrence def sort_desc(arr): # to store sum of all # occurrences of an elements d_sum = {} # to store count of # occurrence of elements d_count = {} # to store final result ans = [] # to store maximum sum of occurrence mx = 0 # Traverse and calculate sum # of occurrence and count of # occurrence of elements of arr[] for x in arr: if x not in d_sum: d_sum[x] = x d_count[x] = 1 else : d_sum[x] + = x d_count[x] + = 1 # sort d_sum in decreasing order of its value l = sorted (d_sum.items(), reverse = True , key = lambda x:(x[ 1 ], x[ 0 ])) # store the final result for x in l: ans + = [x[ 0 ]] * d_count[x[ 0 ]] return ans # Driver Code arr = [ 3 , 5 , 2 , 2 , 3 , 1 , 3 , 1 ] print (sort_desc(arr)) |
C#
using System; using System.Collections.Generic; using System.Linq; class GFG { static List< int > SortDesc( int [] arr) { // to store sum of all // occurrences of an elements Dictionary< int , int > d_sum = new Dictionary< int , int >(); // to store count of // occurrence of elements Dictionary< int , int > d_count = new Dictionary< int , int >(); // to store final result List< int > ans = new List< int >(); // to store maximum sum of occurrence int mx = 0; // Traverse and calculate sum // of occurrence and count of // occurrence of elements of arr[] for ( int i = 0; i < arr.Length; i++) { int x = arr[i]; if (d_sum.ContainsKey(x)) { d_sum[x] += x; d_count[x]++; } else { d_sum[x] = x; d_count[x] = 1; } } // sort d_sum in decreasing order of its value var l = d_sum.OrderByDescending(d => d.Value).ThenBy(d => d.Key); // store the final result foreach ( var kvp in l) { int x = kvp.Key; int count = d_count[x]; while (count > 0) { ans.Add(x); count--; } } return ans; } // Driver code static void Main( string [] args) { int [] arr = { 3, 5, 2, 2, 3, 1, 3, 1 }; Console.WriteLine( string .Join( " " , SortDesc(arr))); } } // This code is contributed by phasing17 |
Javascript
// JavaScript program to sort elements of // arr[] in descending order of sum // of its occurrence function sort_desc(arr) { // to store sum of all // occurrences of an elements let d_sum = {}; // to store count of // occurrence of elements let d_count = {}; // to store final result let ans = []; // to store maximum sum of occurrence let mx = 0; // Traverse and calculate sum // of occurrence and count of // occurrence of elements of arr[] for (let i = 0; i < arr.length; i++) { let x = arr[i]; if (x in d_sum) { d_sum[x] += x; d_count[x]++; } else { d_sum[x] = x; d_count[x] = 1; } } // sort d_sum in decreasing order of its value let l = Object.entries(d_sum).sort( function (a, b) { return b[1] - a[1] || a[0] - b[0]; }); // store the final result for (let i = 0; i < l.length; i++) { let x = l[i][0]; let count = d_count[x]; while (count > 0) { ans.push(parseInt(x)); count--; } } return ans; } // Driver Code let arr = [3, 5, 2, 2, 3, 1, 3, 1]; console.log(sort_desc(arr).join( ' ' )); |
Java
import java.util.*; import java.util.stream.*; class GFG { static List<Integer> sortDesc( int [] arr) { // to store sum of all // occurrences of an elements Map<Integer, Integer> d_sum = new HashMap<>(); // to store count of // occurrence of elements Map<Integer, Integer> d_count = new HashMap<>(); // to store final result List<Integer> ans = new ArrayList<>(); // to store maximum sum of occurrence int mx = 0 ; // Traverse and calculate sum // of occurrence and count of // occurrence of elements of arr[] for ( int i = 0 ; i < arr.length; i++) { int x = arr[i]; if (d_sum.containsKey(x)) { d_sum.put(x, d_sum.get(x) + x); d_count.put(x, d_count.get(x) + 1 ); } else { d_sum.put(x, x); d_count.put(x, 1 ); } } // sort d_sum in decreasing order of its value List<Map.Entry<Integer, Integer> > l = new ArrayList<>(d_sum.entrySet()); Collections.sort(l, (e1, e2) -> { int cmp = e2.getValue().compareTo(e1.getValue()); if (cmp == 0 ) { cmp = e1.getKey().compareTo(e2.getKey()); } return cmp; }); // store the final result for (Map.Entry<Integer, Integer> e : l) { int x = e.getKey(); int count = d_count.get(x); while (count > 0 ) { ans.add(x); count--; } } return ans; } // Driver code public static void main(String[] args) { int [] arr = { 3 , 5 , 2 , 2 , 3 , 1 , 3 , 1 }; List<Integer> sortedList = sortDesc(arr); System.out.println( sortedList.stream() .map(Object::toString) .collect(Collectors.joining( " " ))); } } |
[3, 3, 3, 5, 2, 2, 1, 1]
Time Complexity: O(N*log N).
Space Complexity: O(N).
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!