Sort Array by Increasing Frequency

Medium Hash MapSorting

Problem

Sort the array in increasing order based on the frequency of the values. If two values have the same frequency, sort them in decreasing order by value itself.

Example 1 Input: nums = [1,1,2,2,2,3] Output: [3,1,1,2,2,2] Explain: 3 once, 1 twice, 2 thrice.
Example 2 Input: nums = [2,3,1,3,2] Output: [1,3,3,2,2] Explain: 1 once; 2 and 3 twice → larger (3) first.

Constraints

Approach — Hashing & Counting

This is a Hashing & Counting problem. The idea: store what you've seen in a hash map for O(1) lookups, trading a little space to avoid a nested scan. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time, O(n) space.

Solution code

Python

class Solution:
    def frequencySort(self, nums):
        from collections import Counter
        c = Counter(nums)
        return sorted(nums, key=lambda x: (c[x], x))

Java

class Solution {
    public int[] frequencySort(int[] nums) {
        Map<Integer, Integer> count = new HashMap<>();
        for (int n : nums) count.merge(n, 1, Integer::sum);
        Integer[] boxed = new Integer[nums.length];
        for (int i = 0; i < nums.length; i++) boxed[i] = nums[i];
        Arrays.sort(boxed, (a, b) -> count.get(a).equals(count.get(b))
            ? b - a                       // tie: larger value first
            : count.get(a) - count.get(b)); // else: lower frequency first
        int[] res = new int[nums.length];
        for (int i = 0; i < nums.length; i++) res[i] = boxed[i];
        return res;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Sort Array by Increasing Frequency interactively → ← All solutions