Created
May 29, 2021 09:48
-
-
Save fpaupier/c0308a44a637db563eb05e8f122c4615 to your computer and use it in GitHub Desktop.
692. Top-K Frequent Words
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import Counter | |
import heapq | |
from typing import List | |
class Solution: | |
def topKFrequent(self, words: List[str], k: int) -> List[str]: | |
""" | |
https://leetcode.com/problems/top-k-frequent-words | |
Args: | |
words: List[str] | |
k: int | |
Returns: | |
List[str] of the k most frequent word in words | |
""" | |
count = Counter(words) # O(n) runtime, O(n) space | |
heap = (heapq.nsmallest(k, count.items(), key=lambda item: (-item[1], item[0]))) # O(n*log[k]) runtime, O(n) space | |
return [word for word, _ in heap] # O(k) runtime, O(k) space |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment