</>

347. Top K Frequent Elements

Medium NeetCode 150
Arrays & Hashing Time O(n) Space O(n)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
Arrays & Hashing
Time
O(n)
Space
O(n)

Standard Solution (C++)

SummaryGiven an array of integers, return the k values that appear most often.

Approach

Tally how many times each value occurs, then use bucket sort by frequency so we avoid a full sort.

  • Build a hash map from value to its count.
  • Create buckets indexed by frequency (0..n); place each value in the bucket matching its count.
  • Walk the buckets from highest frequency downward, collecting values until we have k of them.
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> freq;
        for (int x : nums) freq[x]++;
        int n = nums.size();
        vector<vector<int>> buckets(n + 1);
        for (auto& [val, cnt] : freq) buckets[cnt].push_back(val);
        vector<int> result;
        for (int f = n; f >= 1 && (int)result.size() < k; --f) {
            for (int val : buckets[f]) {
                result.push_back(val);
                if ((int)result.size() == k) break;
            }
        }
        return result;
    }
};
Time O(n) Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern