Practice Problem

Top K Frequent Elements

Difficulty: Medium

Find the k most frequent elements in an array using a hash map for counting and bucket sort for efficient selection.

Top K Frequent Elements

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

It is guaranteed that the answer is unique (no ties at the k-th position).

Examples

Example 1:

Input: nums = [1, 1, 1, 2, 2, 3], k = 2
Output: [1, 2]
Explanation: 1 appears 3 times, 2 appears 2 times, 3 appears 1 time.
The two most frequent elements are 1 and 2.

Example 2:

Input: nums = [1], k = 1
Output: [1]

Example 3:

Input: nums = [4, 4, 4, 6, 6, 2, 2, 2, 2], k = 2
Output: [2, 4]
Explanation: 2 appears 4 times, 4 appears 3 times, 6 appears 2 times.
The two most frequent are 2 and 4.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is in the range [1, number of unique elements in the array]
  • The answer is guaranteed to be unique.

Expected Complexity

  • Time: O(n)
  • Space: O(n)
MEDIUM
Arrays
Hash Map / Dictionary
Sorting
Bucket Sort
Top-K Elements
Intermediate

0 views

Solution

Hints

Hint 1
Hint 2
Premium
Hint 3
Premium
Hint 4
Premium