
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.
- Step 1: Count frequency of each element: 1 appears 3 times, 2 appears 2 times, 3 appears 1 time.
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.
- Step 1: There is only one element in the array.
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)
Editorial
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. |
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.