VOOZH about

URL: https://www.geeksforgeeks.org/dsa/potd-solutions-05-nov-23-top-k-frequent-elements-in-array/

⇱ POTD Solutions | 05 Nov’ 23 | Top K Frequent Elements in Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

POTD Solutions | 05 Nov’ 23 | Top K Frequent Elements in Array

Last Updated : 23 Jul, 2025

View all POTD Solutions

Welcome to the daily solutions of our . We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Heaps but will also help you build up problem-solving skills.

👁 5th-nov
POTD Solutions 5 Nov’ 2023
We recommend you to try this problem on our GeeksforGeeks Practice portal first, and maintain your streak to earn Geeksbits and other exciting prizes, before moving towards the solution.

Given a non-empty array nums[] of integers of length N, find the top k elements which have the highest frequency in the array. If two numbers have same frequencies, then the larger number should be given more preference.

Example:

Input: N = 6, nums = {1,1,1,2,2,3}, k = 2
Output: {1, 2}
Explanation: The most frequent element in nums[] is 1 and the second most frequent element is 2.

Input: N = 8, nums = {1,1,2,2,3,3,3,4}, k = 2
Output: {3, 2}
Explanation: Element 3 is the most frequent. Elements 1 and 2 have the same frequency ie. 2. Therefore, in this case, the answer includes the element 2 as 2 > 1.

Create a Map to store element-frequency pair. Map is used to perform insertion and updates in constant time. Then use a priority queue to store the element-frequency pair (Max-Heap). The element which has maximum frequency, comes at the root of the Priority Queue. Remove the top or root of Priority Queue K times and print the element.

Steps-by-step approach:

  • Create a map mp, to store key-value pair, i.e. element-frequency pair.
  • Traverse the array from start to end.
  • For every element in the array update mp[array[i]]++
  • Store the element-frequency pair in a Priority Queue
  • Run a loop k times, and in each iteration remove the root of the priority queue and print the element.

Below is the implementation of the above approach:

Time Complexity: O(K log D + D log D), where D is the count of distinct elements in the array. 
Auxiliary Space: O(D), where D is the count of distinct elements in the array. 

Comment