Basic example
Input
nums = [1,1,1,2,2,3], k = 2
Output
[1, 2]
1 appears 3 times, 2 appears 2 times, 3 appears once. The top 2 are [1, 2].
Full lesson preview
Return the k most frequent elements from an integer array using hashing and sorting for determinism.
Problem statement
Task
Examples
Input
nums = [1,1,1,2,2,3], k = 2
Output
[1, 2]
1 appears 3 times, 2 appears 2 times, 3 appears once. The top 2 are [1, 2].
Input format
Output format
Constraints
Samples
Input
nums = [4,4,4,6,6,5,5,5], k = 2
Output
[4, 5]
4 and 5 both appear 3 times; tie broken by smaller value first (4 then 5).