Tutorialspoint
Problem
Solution
Submissions

Top K Frequent Elements

Certification: Intermediate Level Accuracy: 100% Submissions: 1 Points: 10

Write a JavaScript program to find the k most frequent elements in an array. Given an integer array nums and an integer k, return the k most frequent elements. The answer can be returned in any order.

Example 1
  • Input: nums = [1,1,1,2,2,3], k = 2
  • Output: [1,2]
  • Explanation:
    • Count the frequency of each element in the array.
    • Element 1 appears 3 times, element 2 appears 2 times, element 3 appears 1 time.
    • We need the top 2 most frequent elements.
    • Elements 1 and 2 are the most frequent, so we return [1,2].
Example 2
  • Input: nums = [1], k = 1
  • Output: [1]
  • Explanation:
    • The array contains only one element.
    • Element 1 appears 1 time.
    • We need the top 1 most frequent element.
    • The only element 1 is returned as [1].
Constraints
  • 1 ≤ nums.length ≤ 10^5
  • -10^4 ≤ nums[i] ≤ 10^4
  • k is in the range [1, number of unique elements in array]
  • Time Complexity: O(n log k)
  • Space Complexity: O(n)
Hash MapHeapPwCTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a hash map to count the frequency of each element
  • Use a min-heap to keep track of the k most frequent elements
  • Iterate through the frequency map and maintain a heap of size k
  • If heap size exceeds k, remove the least frequent element
  • Extract all elements from the heap to get the final result

Steps to solve by this approach:

  Step 1: Create a hash map to store the frequency of each element in the input array.

 Step 2: Iterate through the array and count occurrences of each element using the frequency map.
 Step 3: Convert the frequency map to an array of [element, frequency] pairs for easier manipulation.
 Step 4: Sort the array of pairs in descending order based on frequency values.
 Step 5: Extract the first k elements from the sorted array to get the most frequent elements.
 Step 6: Create a result array containing only the element values (not frequencies).
 Step 7: Return the result array containing the k most frequent elements.

Submitted Code :