Find top k frequent elements in an array of integers. Let’s first understand the problem statement and the we will solve this problem using multiple approaches.
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: arr = {3, 4, 4, 4, 7, 7}, k = 2
Output: {4, 7}
Two most frequent elements are 4 and 7.
Example 2:
Input: arr = {3}, k = 1
Output: {3}
NOTE:
* k is always valid, 1 ≤ k ≤ number of unique elements.
* The time complexity must be better than O(nlogn), where n is the array’s size.
* It’s guaranteed that the answer is unique, in other words, the set of the top k frequent elements is unique.
* Answer can be returned in any order.