The Blind 75 Leetcode Series: Top K Frequent Elements
3 min readOct 31, 2023
Today, we are working on 347. Top K Frequent Elements
Given an integer array
nums
and an integerk
, return thek
most frequent elements. You may return the answer in any order.
The problem seems simple, but there are some corner cases we want to cover.
- Do we expect empty list?
- Do we expect
k
being greater than the number of distinct elements in the list, in that case, do we return all distinct elements? - If there are more elements that appear at the same frequency than k, what do we return? Say [1, 1, 2, 3, 4, 5] and k = 3, all elements have the same frequency and they are all top frequency (which is 1), what do we return?
If the interviewer tells us that
- Yes, we do expect empty list
- If k > number of distinct elements, return all these elements
- In scenario 3, return any k elements as long as 1 is returned.
Okay, here we go.
We can quickly check for empty list and get first scenario out of the way. For the rest, we can first build a…