Skip to content

Instantly share code, notes, and snippets.

@fpaupier
Created May 29, 2021 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fpaupier/c0308a44a637db563eb05e8f122c4615 to your computer and use it in GitHub Desktop.
Save fpaupier/c0308a44a637db563eb05e8f122c4615 to your computer and use it in GitHub Desktop.
692. Top-K Frequent Words
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