# Sort an array in descending order based on the sum of its occurrence

• Last Updated : 24 Jun, 2021

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:

1. 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.
2. After doing the mapping sort the dictionary in descending order based on their values not keys. In case of tie, sort based on values.
3. 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:

## 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))`

Output:

`[3, 3, 3, 5, 2, 2, 1, 1]`

Time Complexity: O(N*log N).
Space Complexity: O(N).

My Personal Notes arrow_drop_up
Recommended Articles
Page :