You are given an integer array nums and an integer k.
Your task is to return the k most frequent elements in the array.
-
Count how many times each number appears.
-
Return the elements with the highest frequencies.
-
Order does not matter.
This is a classic frequency + heap/hashmap problem.
An array nums
An integer k
An array of k elements that appear most frequently.
Example 1
Input:
nums = [1,1,1,2,2,3]
k = 2
Output:
[1,2]
Explanation:
1 appears 3 times, 2 appears 2 times → they are top 2.
Example 2
Input:
nums = [1]
k = 1
Output:
[1]
-
1 ≤ nums.length ≤ 10⁵
-
k ≥ 1
-
Answer must be among the unique elements
-
Use a frequency map to count occurrences
-
Use a heap OR bucket sort to pick top k
-
Python’s heapq supports min-heaps; push (-frequency, value) OR use a size-k heap
Step 1: Count frequencies using a dictionary
Step 2: Use a heap (or buckets) to extract k elements with the highest frequency
Step 3: Return those elements
This problem tests knowledge of hashmaps and priority queues.