Explanation
Top K Frequent Elements is a Medium interview problem tagged [Array, Hash Table, Heap]. The winning approach is typically **Heap**.
#347
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Example 1
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
1 appears 3 times, 2 appears 2 times.
Example 2
Input: nums = [1], k = 1
Output: [1]
Only one element.
Top K Frequent Elements is a Medium interview problem tagged [Array, Hash Table, Heap]. The winning approach is typically **Heap**.
O(log k) updates beat full sorts when you only need extremes.
Use a priority queue for Top-K, scheduling, or Dijkstra-style extraction of minima.
Pattern-level skeleton only — not this problem’s exact answer. Adapt it to the statement.
Time: O(n log n)
Space: O(n)
Before coding, restate the problem, name the pattern (Heap), and write the invariant or DP state in one sentence.
Got it?
Mark #347 Top K Frequent Elements as understood when the pattern clicks.