Skip to content

Commit f24f52a

Browse files
committed
O(nlogk) time and O(n) space using max heap
1 parent 4297e3a commit f24f52a

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

692. Top K Frequent Words/692. Top K Frequent Words_nlogk_solution.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,30 @@
1+
"""
2+
Given an array of strings words and an integer k, return the k most frequent strings.
3+
4+
Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.
5+
6+
7+
8+
Example 1:
9+
10+
Input: words = ["i","love","leetcode","i","love","coding"], k = 2
11+
Output: ["i","love"]
12+
Explanation: "i" and "love" are the two most frequent words.
13+
Note that "i" comes before "love" due to a lower alphabetical order.
14+
Example 2:
15+
16+
Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
17+
Output: ["the","is","sunny","day"]
18+
Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
19+
20+
21+
Constraints:
22+
23+
1 <= words.length <= 500
24+
1 <= words[i] <= 10
25+
words[i] consists of lowercase English letters.
26+
k is in the range [1, The number of unique words[i]]
27+
"""
128
class Solution:
229
def topKFrequent(self, words: List[str], k: int) -> List[str]:
330
hmap = collections.Counter(words)

0 commit comments

Comments
 (0)