In the North American SDE industry, interview is an important part for job seekers to show their skills, and Google, as the industry leader, its interview questions often become the focus of attention of job seekers. Today, we will discuss the classic Google question in North American interviews - “Find Top K Largest Element”, and share the problem solving skills.
Question Description The question requires that given an array of integers, nums, and an integer, k, return the k most frequently occurring elements of the array, and the answers can be in any order. For example, given nums = [1,1,1,2,2,3] and k = 2, the output should be [1,2].

Solution Ideas:
A common idea for solving this problem is to utilize a Min Heap or Max Heap. first count the frequency of each element through a Map, and then store the elements and their frequency information into the Min Heap. The heap is continuously adjusted to ensure that the k elements with the highest frequencies are always retained in the heap, and an array of results is constructed. However, the time complexity of this method is O (NlogN).
Optimization Schemes:
To optimize the time complexity, we can borrow the idea of Quick Sort. In Quick Sort, each iteration splits the elements into two sides based on the selected Pivot. For this question, we are comparing the frequency of the elements rather than the size of the numbers. By choosing the right Pivot (the Kth frequent element), you can quickly locate the Top K elements. The specific operation is to carry out a Partition, according to the frequency of the elements into two parts of the array, and then determine the number of elements on the right side of the Pivot and the relationship between k, to decide the next step in the left or right to continue to look for, until we find the Kth frequent element, and then get the Top K elements.
Code Implementation:

Complexity Analysis
The average time complexity of this optimized method is O (N), but in the worst case it is still O (N^2). The space complexity is O (N) and N is the length of the input array. This is the interpretation of the classic North American Google interview questions, did you learn it?