PIXELBANKv8.2.1
Menu

Top K Frequent Elements

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

Output space-separated, sorted.

Example:

Input:
1,1,1,2,2,3
2
Output:
1 2
Reasoning:
  • First, we count the frequency of each element in the array: 1 appears 3 times, 2 appears 2 times, and 3 appears 1 time.
  • Then, we sort the elements by their frequency in descending order: 1 (33 times), 2 (22 times), 3 (11 time).
  • Next, we select the top k=2k = 2 most frequent elements, which are 1 and 2.
  • The final output is the selected elements in sorted order: 1 2

Constraints:

  • 1 <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is always valid (1 <= k <= number of unique elements)
Editor

Test Results

0/0
Run code to see test results.