The Blind 75 Leetcode Series: Top K Frequent Elements

Jonathan Chao
3 min readOct 31, 2023
Photo by Chris Ried on Unsplash

Today, we are working on 347. Top K Frequent Elements

Given an integer array nums and an integer k, return the k 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.

  1. Do we expect empty list?
  2. Do we expect k being greater than the number of distinct elements in the list, in that case, do we return all distinct elements?
  3. 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

  1. Yes, we do expect empty list
  2. If k > number of distinct elements, return all these elements
  3. 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…

--

--

Jonathan Chao
Jonathan Chao

Written by Jonathan Chao

I am a software developer who has been in this industry for close to a decade. I share my experience to people who are or want to get into the industry

No responses yet