can anyone explain How Sorted function is working here especially that second part " -items[0] "

Viewed 12
# code to print elements in a list on the basis of frequency they occurr
class Solution:
def frequencySort(self, nums: List[int]) -> List[int]:
    hashMap = {}
    res = []
    # getting the frequency
    for i in nums:
        if i in hashMap:
            hashMap[i] = hashMap.get(i) + 1
        else:
            hashMap[i] = 1
    # sorting on the basis of value in dictionary
    hashMap = sorted(hashMap.items(), key=lambda item: (item[1], -item[0]))

    for k,v in hashMap:
        res.extend([k]*v)
    
    return res

this code returns a list on the basis of the frequency the element appears in the list it stores the count of each element then sorts the elements on the basis of their frequency and then append the elements the time they appear

0 Answers
Related