bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 692. Top K Frequent Words

692. Top K Frequent Words

Leetcode Solutions

Approach: Min Heap

  1. Create a frequency map to count the occurrences of each word.
  2. Create a min heap that can hold up to k elements and is ordered by frequency and lexicographical order.
  3. Iterate over the frequency map and for each word-frequency pair: a. If the heap size is less than k, add the current word-frequency pair to the heap. b. Otherwise, if the current frequency is higher than the root of the heap, or the frequency is the same but the word is lexicographically smaller, replace the root with the current word-frequency pair and heapify.
  4. Once all words have been processed, extract the elements from the heap and add them to the result list in reverse order since the heap is a min heap.
  5. Return the result list.
UML Thumbnail

Approach: Brute Force

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...