Skip to content

Commit ee3d660

Browse files
authored
Create Top K frequent Words.py
1 parent a785d21 commit ee3d660

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

medium/Top K frequent Words.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#692. Top K Frequent Words
2+
class Solution:
3+
def topKFrequent(self, words: List[str], k: int) -> List[str]:
4+
ans = []
5+
bucket = [[] for _ in range(len(words) + 1)]
6+
7+
for word, freq in Counter(words).items():
8+
bucket[freq].append(word)
9+
10+
for b in reversed(bucket):
11+
for word in sorted(b):
12+
ans.append(word)
13+
if len(ans) == k:
14+
return ans

0 commit comments

Comments
 (0)