> For the complete documentation index, see [llms.txt](https://zedive.gitbook.io/project-l/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zedive.gitbook.io/project-l/part-1/basic_data_structure/heap/top-k-frequent-elements.md).

# Top K Frequent Elements

## Question ([LC.347](https://leetcode.com/problems/top-k-frequent-elements/description/))

> Given a list of integers, return the top k most frequent values.&#x20;

## Example

```
I: [1, 1, 1, 2, 2, 3], k = 2 
O: [1, 2] 

I: [3, 2, 1], k = 1 
O: the answer is not unique 
```

## Simple Heap

```python
def topKFrequent(self, nums: List[int], k: int) -> List[int]:

    # use a hash map to reduce this problem to a common top k problem

    if len(nums) == 0 or k == 0:
        return []

    num_dict: Dict[int, int] = {}

    for num in nums:
        if num in num_dict:
            num_dict[num] = num_dict[num] + 1
        else:
            num_dict[num] = 1

    # use a min heap of k elements

    min_heap = []

    for key in num_dict:
        if len(min_heap) < k:
            heapq.heappush(min_heap, (num_dict[key], key))
        elif num_dict[key] > min_heap[0][0]:
            heapq.heappop(min_heap)
            heapq.heappush(min_heap, (num_dict[key], key))

    return [k for (v, k) in min_heap]
```

Worst case O(nlogk) time and O(n) + O(k) space&#x20;

## Quick Select

## Bucket Sort


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zedive.gitbook.io/project-l/part-1/basic_data_structure/heap/top-k-frequent-elements.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
