# Top K Frequent Elements

## Problem

Given a non-empty array of integers, return the **k** most frequent elements.

{% hint style="info" %}
For example:

```
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
```

```
Input: nums = [1], k = 1
Output: [1]
```

{% endhint %}

### Thought Process

* This problem is very similar to how we solved K Closest Points but in this problem we are storing (frequency, number) pairs in our heap.

* We want the top K elements, this is why a **min-heap** is good.

## Solution

```
from heapq import *
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        freq = {}
        heap = []
        
        for i in nums:
            if i not in freq:
                freq[i] = 0
            freq[i]+=1
        
        for num, count in freq.items():
            heappush(heap, (count, num))
            if len(heap) > k:
                heappop(heap)
        
        res = []
        for i in range(len(heap)):
            res.append(heap[i][1])
        return res
                
```

## Key Points

* Using min-heap to store elements according to their frequency count so we get the top K

* Storing the frequency count and number together in **pairs** in the heap

## Time Complexity

* **Time:** $$O(N+N\*log(K))$$&#x20;
* **Space:** $$O(N)$$ because even though we are storing only ‘K’ numbers in the heap. For the frequency map, however, we need to store all the ‘N’ numbers.


---

# Agent Instructions: 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://joshualbarb.gitbook.io/leetcode-problems/top-k-elements-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.
