Top K Frequent Elements

medium

Find the k most frequent elements using bucket sort

Top K Frequent Elements

Key Insight

Count each value first, then select K values with largest frequency; frequency drives the ranking order.

Step 1Count Frequencies
freq(1)=3freq(2)=2freq(3)=1
String s (building)
String t
1
0
2
1
3
2
HashMap
1:3
2:2
3:1
Looking for:1

Scan nums and store counts per value.

1 / 3

Learn the Pattern

Practice the Code

Step-by-Step Walkthrough: Top K Frequent Elements

Count each value first, then select K values with largest frequency; frequency drives the ranking order.

  1. Count Frequencies

    Scan nums and store counts per value.

  2. Build Ranked List

    Convert map entries to (value, frequency) pairs and order by frequency descending.

  3. Take Top K

    Keep only first K pairs and return their values.