Sort Array by Increasing Frequency

easy array hash map sorting

Problem

Given an integer array, sort it in increasing order based on the frequency of values. If multiple values have the same frequency, sort them in decreasing order.

Inputnums = [1,1,2,2,2,3]
Output[3,1,1,2,2,2]
3 occurs once, 1 occurs twice, 2 occurs thrice.

from collections import Counter

def frequency_sort(nums):
    c = Counter(nums)
    return sorted(nums, key=lambda x: (c[x], -x))
function frequencySort(nums) {
  const c = new Map();
  for (const x of nums) c.set(x, (c.get(x) || 0) + 1);
  return nums.slice().sort((a, b) => c.get(a) - c.get(b) || b - a);
}
class Solution {
    public int[] frequencySort(int[] nums) {
        Map<Integer, Integer> c = new HashMap<>();
        for (int x : nums) c.merge(x, 1, Integer::sum);
        return Arrays.stream(nums).boxed()
            .sorted((a, b) -> c.get(a) != c.get(b) ? c.get(a) - c.get(b) : b - a)
            .mapToInt(Integer::intValue).toArray();
    }
}
vector<int> frequencySort(vector<int>& nums) {
    unordered_map<int,int> c;
    for (int x : nums) c[x]++;
    sort(nums.begin(), nums.end(), [&](int a, int b) {
        return c[a] != c[b] ? c[a] < c[b] : a > b;
    });
    return nums;
}
Time: O(n log n) Space: O(n)