> For the complete documentation index, see [llms.txt](https://maksimdan.gitbook.io/interview-practice-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/347_top_k_frequent_elements.md).

# 347 Top K Frequent Elements

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

```
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
`
```

Note:

* You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
* Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

```cpp
vector<int> topKFrequent(vector<int>& nums, int k) {
    vector<int> most_freq;
    unordered_map<int, int> hashmap;

    for (int i : nums) {
        // not found, insert new number
        if (hashmap.find(i) == hashmap.end()) {
            hashmap.insert({ { i },{ 1 } });
        }

        // found update frequency
        hashmap.find(i)->second++;
    }

    for (int i = 0; i < k; i++) {
        int max = 0;
        int key = 0;
        for (auto &i : hashmap) {
            if (i.second > max) {
                max = i.second;
                key = i.first;
            }
        }
        hashmap.erase(hashmap.find(key));
        most_freq.push_back(key);
    }

    return most_freq;
}
```


---

# 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, and the optional `goal` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/347_top_k_frequent_elements.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
