↻one more pass.
Heaps · Medium

Top K Frequent Elements: the idea to remember.

Return any ordering of the k most frequent distinct values in an integer array.

Solve on LeetCode ↗

The core insight

Count occurrences, put values into frequency buckets, then scan buckets from the highest frequency down.

Why it works

A bucket index is the exact occurrence count. Visiting buckets in descending order visits values in nonincreasing frequency.

The mistake to avoid

Do not sort the original array or return repeated copies of a frequent value. k is assumed valid and any order is accepted.

Time: O(n) expectedSpace: O(n)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int[] topKFrequent(int[] nums, int k) {
    Map<Integer, Integer> count = new HashMap<>();
    for (int n : nums) count.merge(n, 1, Integer::sum);
    List<List<Integer>> buckets = new ArrayList<>();
    for (int i = 0; i <= nums.length; i++) buckets.add(new ArrayList<>());
    for (int n : count.keySet()) buckets.get(count.get(n)).add(n);
    int[] out = new int[k]; int next = 0;
    for (int f = nums.length; f > 0 && next < k; f--)
        for (int n : buckets.get(f)) { out[next++] = n; if (next == k) break; }
    return out;
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.