692. Top K Frequent Words
All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : July 10, 2024
Last updated : July 10, 2024
Related Topics : Hash Table, String, Trie, Sorting, Heap (Priority Queue), Bucket Sort, Counting
Acceptance Rate : 58.183 %
Sorting and heapifying are both nlogn so i thought it would be simpler this way since it uses native functions vs us iterating and flipping priorities to negative to create a max heap via the 2nd value in each tuple or having to manually add them
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
counter = list(Counter(words).items())
counter.sort()
counter.sort(key=lambda x: x[1], reverse=True)
return [counter[x][0] for x in range(k)]