Code
Loading editor...
Tap Analyze to see visualization
Click Analyze to visualize
See step-by-step execution, variables, and output
Variables
Run code to see variables
Output
Console output will appear here
Click Analyze to visualize
See step-by-step execution, variables, and output
Run code to see variables
Console output will appear here
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.
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