easyBasic Hashing

Sort Array by Increasing Frequency

Order array values by increasing frequency. Values with equal frequencies must appear in decreasing numerical order. Preserve all occurrences.

Work through the cases

3 examples

Input notation

One nonempty line of space-separated integers.

Expected result

The reordered values separated by spaces.
Case 1

Input

4 4 2 3 3 3

Expected output

2 4 4 3 3 3
Case 2

Input

8 2 8 2

Expected output

8 8 2 2
Case 3

Input

-1 -1 0 2

Expected output

2 0 -1 -1

These notes use simplified input/output notation. The linked platform defines the method signature and judge format.

FROM IDEA TO IMPLEMENTATION

Understand the approach.

Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.

The order is increasing frequency, then decreasing value on ties. n ≤ 100, so count then sort with a key. A counter (or a shifted array) yields cnt; the sort key is (cnt[x], -x).

class Solution {
    public int[] frequencySort(int[] nums) {
        int[] cnt = new int[201];
        List<Integer> t = new ArrayList<>();
        for (int v : nums) {
            v += 100;
            ++cnt[v];
            t.add(v);
        }
        t.sort((a, b) -> cnt[a] == cnt[b] ? b - a : cnt[a] - cnt[b]);
        int[] ans = new int[nums.length];
        int i = 0;
        for (int v : t) {
            ans[i++] = v - 100;
        }
        return ans;
    }
}

Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.

Solutions adapted from Doocs / LeetCode contributors, licensed under CC BY-SA 4.0. Formatting changed; TypeScript versions converted to JavaScript. Supplemental implementations and approach notes added. Adapted solution material is available under the same license.