> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Top K Frequent Words Python Solution

> Tested Python solution for LeetCode 692 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 692, Medium. Topics: Array, Hash Table, String, Trie, Sorting, Heap (Priority Queue), Bucket Sort, Counting. [View on LeetCode](https://leetcode.com/problems/top-k-frequent-words/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 692   # by problem number
lcpy gen -s top_k_frequent_words   # by problem name
```

## Problem

Given an array of strings `words` and an integer `k`, return *the* `k` *most frequent strings*.

Return the answer **sorted** by **the frequency** from highest to lowest. Sort the words with the same frequency by their **lexicographical order**.

### Examples

```
Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
```

```
Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
```

### Constraints

* `1 <= words.length <= 500`
* `1 <= words[i].length <= 10`
* `words[i]` consists of lowercase English letters.
* `k` is in the range `[1, The number of unique words[i]]`

**Follow-up:** Could you solve it in `O(n log(k))` time and `O(n)` extra space?

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/top_k_frequent_words/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/top_k_frequent_words/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n log k) - each word processed with O(log k) heap operations
    # Space: O(n + k) - Counter takes O(n), heap takes O(k)
    def top_k_frequent(self, words: list[str], k: int) -> list[str]:
        import heapq
        from collections import Counter

        count = Counter(words)
        # Min-heap of size k: (freq, word)
        # Keep least frequent at top, reverse lexicographic for ties
        heap: list[tuple[int, str]] = []

        for word, freq in count.items():
            if len(heap) < k:
                # Min-heap: (freq, -word) for reverse lexicographic order
                heapq.heappush(heap, (freq, word))
            else:
                min_freq, min_word = heap[0]
                # Replace if current word has higher priority
                if freq > min_freq or (freq == min_freq and word < min_word):
                    heapq.heapreplace(heap, (freq, word))

        # Extract and sort results
        result = list(heap)
        result.sort(key=lambda x: (-x[0], x[1]))
        return [word for _, word in result]
```

## Complexity

| Time                                                           | Space                                          |
| -------------------------------------------------------------- | ---------------------------------------------- |
| O(n log k) - each word processed with O(log k) heap operations | O(n + k) - Counter takes O(n), heap takes O(k) |

## Tags

[Grind](/catalog/grind).
