array and hashmap May 7, 2023

Sort array by increasing frequency

Time O(nlog(n)) Space O(n) Open original problem

We will use a hashmap to store the frequency of each number. Then we will sort the array by the frequency of each number. If the frequency of two numbers is the same, we will sort them by the value of the number. Finally, we will return the sorted array.

class Solution:
    def frequencySort(self, nums: List[int]) -> List[int]:
        counter = collections.Counter(nums)
        return sorted(nums, key=lambda x: (counter[x], -x))

Time complexity: O(nlog(n))
Space complexity: O(n)