Given an unsorted array of integers which may contain repeated elements, sort the elements in ascending order of sum of its occurrence and print only distinct elements. If there exist more than one element whose sum of occurrences are same then, the one which is smaller, will come first.
Examples:
Input : arr[] = [8, 2, 4, 2, 4, 2, 1] Output : arr[] = [1, 2, 4, 8] Explaination : Here, 2 appears 3 times, 4 appears 2 times, 1 appears 1 times and 10 appears 1 times. 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 8 = 8 * 1 = 8, Sum of all occurrences of 1 = 1 * 1 = 1. Therefore sorting the array in ascending order based on the above sum = [1, 2, 4, 8] Input : arr[] = [9, 4, 3, 3, 3, 2, 4, 2] Output : arr[] = [2, 4, 3, 9]
Recommended: Applications of Operating System
Approach:
- Create a map that will map elements to it appearence i.e. 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 asscending order based on their values. In case of tie, sort based on keys.
- Finaly copy the sorted dictionary keys in final output array.
Implementation:
#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 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 else: d_sum[x] += x #sort d_sum in decreasing order of its value l=sorted(d_sum.items(), key= lambda x:(x[1],x[0])) #store the final result for x in l: ans += [x[0]] return ans #Driver Code arr = [9, 4, 3, 3, 3, 2, 4, 2] print("arr :",sort_desc(arr))
Output :
arr : [2, 4, 3, 9]
Time complexity: O(nlogn)
Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.