Trace through nums = [3, 0, 1, 0] with k = 1.
Count frequencies: {3: 1, 0: 2, 1: 1}.
Create buckets of size :
- Bucket
1:[3, 1](elements appearing once) - Bucket
2:[0](elements appearing twice) - Buckets
0, 3, 4: empty
Scan from highest bucket (index ) down. Bucket 4: empty. Bucket 3: empty. Bucket 2: found [0]. You need k = 1 element, so return [0].
Counting takes . Building buckets takes . Scanning buckets takes in the worst case. Total: time.
The hash map and bucket array each use space.