Top K Frequent Elements
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Return the k values that appear most often.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1First count each value. What do you do with the counts?
- Hint 2A count can be at most the size of the list. Could you index a shelf by count?
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
A canteen records every order on a tally sheet. To find the top 2 snacks you do not sort all 50 snack names. You put up a shelf with slots labelled "ordered 1 time, 2 times, 3 times..." and drop each snack into the slot of its count. Then read the shelf from the highest slot downward until you have 2.
- The obvious way
Count, sort all distinct values by count, take k: O(n log n).
- The key insight
A value can appear at most n times, so make a shelf with n+1 slots where slot c holds the values that appeared exactly c times. Read the shelf from the top slot downward and collect k values: no sorting, O(n).
- The algorithm
- Count each value on a tally sheet (dictionary).
- Make a shelf with one slot per possible count; put each value in the slot of its count.
- Read the shelf from the highest slot down, collecting values until you have k.
Watch it run
Examplenumbers = [1, 1, 1, 2, 2, 3], k = 2
Tally: 1 appears 3 times, 2 appears 2 times, 3 appears once.
{1: 3, 2: 2, 3: 1}Where people slip
- The shelf needs n+1 slots because a count equal to n is possible.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
from collections import Counter
def top_k_frequent(nums, k):
tally = Counter(nums) # value -> how many times
shelf = [[] for _ in range(len(nums) + 1)] # shelf[c] = values seen c times
for value, count in tally.items():
shelf[count].append(value)
answer = []
for count in range(len(shelf) - 1, 0, -1): # highest slot first
for value in shelf[count]:
answer.append(value)
if len(answer) == k:
return answer
return answer
# alternative: heapq.nlargest(k, tally, key=tally.get) -> O(n log k)Now close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.