Select K Elements with Highest Occurrence Count
Heaps, Sorting & SearchAuto-graded · 22 test casesLast updated
Tests frequency counting with hash maps and efficient selection of top elements using heap-based algorithms.
You are given an array of integers and a positive integer k. Your task is to identify and return the k numbers that appear most frequently in the array.
Each number should appear at most once in your output. The order of numbers in the result does not matter.
Write a function that takes an integer array and returns the k elements with the highest occurrence counts.
Constraints
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^41 <= k <= number of distinct elements in nums- There is always exactly one valid answer (no ambiguous ties at position k)
Examples
Example 1
Input: select_k_most_frequent([1, 1, 1, 2, 2, 3], 2)
Output: [1, 2]
Example 2
Input: select_k_most_frequent([1], 1)
Output: [1]
Hints
Hint 1
Start by tallying how many times each distinct number appears in the array
Hint 2
You don't need to sort all unique elements—just identify the top k by frequency
Hint 3
Python's heapq module provides efficient functions for finding the largest items without full sorting
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution breaks into two phases:
-
Frequency Counting: Build a hash map that records how many times each distinct number appears. This requires a single pass through the input array.
-
Top-K Selection: From all distinct numbers, identify the
kwith the highest frequencies. Rather than sorting all distinct elements (which would cost O(U log U) where U is the count of unique values), we use a heap-based selection that costs only O(U log k).
Python's heapq.nlargest function implements this efficiently by maintaining a min-heap of size k. As it processes each element, it keeps only the k largest items seen so far. This avoids the overhead of sorting elements we don't need.
The output is automatically distinct because we're selecting from the keys of our frequency map, where each number appears exactly once.
Correctness
- Accurate counting: The Counter correctly tallies each element's occurrences in linear time
- Correct selection:
heapq.nlargestwith a custom key function returns exactly thekitems with the greatest frequencies, equivalent to taking the firstkelements from a descending sort by frequency - No ambiguity: The problem guarantees a unique answer, so there are no ties at the boundary position
k
Complexity
Let N = length of input array and U = number of distinct values.
- Time: O(N) to build the frequency map, then O(U log k) for heap-based selection. Overall: O(N + U log k), which simplifies to O(N log k) in typical cases.
- Space: O(U) for the frequency map, plus O(k) for the heap and result, so O(U) total.
Alternative: Linear-Time Bucket Sort
Since frequencies range from 1 to N, you can create N+1 buckets where bucket[f] stores all numbers appearing exactly f times. Then iterate from frequency N down to 1, collecting numbers until you have k of them. This achieves O(N) time and O(N) space.
from collections import Counter
from typing import List
import heapq
def select_k_most_frequent(nums: List[int], k: int) -> List[int]:
counts = Counter(nums)
return [num for num, freq in heapq.nlargest(k, counts.items(), key=lambda item: item[1])]