Solutions for Sorting by Frequency

    • @Glenndiuby
    • @Michael, submitted in Python 3, achived 100% score
    from collections import defaultdict
    import json
    # Sort by Frequency
    
    
    def solve(arr):
        n = len(arr)
        # arr -> Array to be sorted
        # n   -> Length of Array
    
        # d is a hashmap(referred as dictionary in python)
        d = defaultdict(lambda: 0)
        for i in range(n):
            d[arr[i]] += 1
    
        # Sorting the array 'arr' where key
        # is the function based on which
        # the array is sorted
        # While sorting we want to give
        # first priority to Frequency
        # Then to value of item
        arr.sort(key=lambda x: (-d[x], x))
    
        return (arr)