Skip to content

Commit f5e705e

Browse files
committed
Top K frequent words solution to problem form Daily interview problem
1 parent 8a02abc commit f5e705e

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'''
2+
Top K frequent words - Daily Interview Pro
3+
4+
Given a non-empty list of words, return the k most frequent words.
5+
The output should be sorted from highest to lowest frequency,
6+
and if two words have the same frequency, the word with lower
7+
alphabetical order comes first. Input will contain only lower-case letters.
8+
9+
Example:
10+
Input: ["daily", "interview", "pro", "pro", "for", "daily", "pro", "problems"], k = 2
11+
Output: ["pro", "daily"]
12+
'''
13+
import heapq
14+
def top_k_frequent(words, k):
15+
d = {}
16+
for word in words:
17+
if word in d:
18+
d[word] += 1
19+
else:
20+
d[word] = 1
21+
heap = []
22+
for word in d:
23+
heapq.heappush(heap, [-d[word], word])
24+
answer = []
25+
for i in range(k):
26+
pair = heapq.heappop(heap)
27+
answer.append(pair[1])
28+
return answer
29+
30+
# Test
31+
words = ["daily", "interview", "pro", "pro", "for", "daily", "pro", "problems"]
32+
k = 2
33+
print top_k_frequent(words, k)
34+
# ['pro', 'daily']
35+

0 commit comments

Comments
 (0)