# CODE

```python
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        # Get count of each number
        count = {}
        for n in nums:
            count[n] = 1 + count.get(n, 0)
            
        # Create a dict freq -> all the numbers with that freq
        freq = {}
        for n, f in count.items():
            if f not in freq:
                freq[f] = []
            freq[f].append(n)

        res = []
        for f in range(len(nums), 0, -1):
            # get all the numbers for the freq starting with highest
            if f in freq:
                for n in freq[f]:
                    res.append(n)
                    if len(res) == k:
                        return res
```


---

# 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://chiragjain.gitbook.io/neetcode/347-top-k-frequent-elements/code.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.
