Top K Frequent Elements

Med
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Top K Frequent Elements

Approach

First count element frequencies using a hash map. Then use bucket sort where the bucket index represents frequency and the bucket contents are elements with that frequency. Collect elements from the highest-frequency buckets until k elements are gathered.

Complexity Analysis

Time
O(n)
Space
O(n)

Pattern

Frequency Count + Bucket Sort

Why It Works

Bucket sort avoids the O(n log n) cost of comparison-based sorting. Since frequencies are bounded by array length, creating buckets indexed by frequency enables linear-time extraction of the top k elements.

Updated Feb 2026