Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Top K Frequent Elements

LeetCode #347Medium
Frequency map · return the k most common values

Given an integer array and a number k, return the k most frequent elements. The answer is guaranteed to be unique; it may be returned in any order.

Asked atAmazonFacebookYelp
step 1 / 23
1
1
1
2
2
3
[0][1][2][3][4][5]
Count + sort
1given arr, k; count ← {}
2for v in arr:
3 count[v] ← count[v] + 1
4entries ← sort count by frequency desc
5result ← first k values of entries
6return result
state
  • k2
  • count{}

line 1Return the 2 most frequent values in the array. First we need to know how often each value appears.