PIXELBANKv9.1.0
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
  • 1 <= k <= number of unique elements
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.