Tutorialspoint
Problem
Solution
Submissions

Top K Frequent Elements in an Array

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

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

Example 1
  • Input: nums = [1,1,1,2,2,3], k = 2
  • Output: [1,2]
  • Explanation:
    •  Step 1: Count frequency of each element: 1 appears 3 times, 2 appears 2 times, 3 appears 1 time.
    •  Step 2: The two most frequent elements are 1 and 2.
    •  Step 3: Return [1,2] as the result.
Example 2
  • Input: nums = [1], k = 1
  • Output: [1]
  • Explanation:
    •  Step 1: There is only one element in the array.
    •  Step 2: Element 1 appears 1 time.
    •  Step 3: Return [1] as it's the most frequent (and only) element.
Constraints
  • 1 ≤ nums.length ≤ 10^5
  • -10^4 ≤ nums[i] ≤ 10^4
  • k is in the range [1, the number of unique elements in the array]
  • Time Complexity: O(n log k)
  • Space Complexity: O(n)
ArraysWalmartPhillips
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

  • First, count the frequency of each element using a hash map approach.
  • Use arrays to store unique elements and their frequencies.
  • Sort the elements based on their frequencies in descending order.
  • Take the first k elements from the sorted array.
  • Return the k most frequent elements.

Steps to solve by this approach:

 Step 1: Create a structure to hold element and its frequency.
 Step 2: Count the frequency of each unique element in the input array.
 Step 3: Store unique elements and their frequencies in an array of structures.
 Step 4: Sort the array by frequency in descending order using qsort.
 Step 5: Create result array and copy the first k elements from sorted array.
 Step 6: Set the return size to k and return the result array.
 Step 7: Free allocated memory in the main function after use.

Submitted Code :