 All Problems
Top K Frequent Elements
medium
heap
hash map
arrays
amazon
facebook
google
microsoft

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

Example 1:

Input:
1 1 1 2 2 3
2
Output: 1 2

Example 2:

Input:
1
1
Output: 1

Constraints:

  • 1 ≤ nums.length ≤ 10⁵
  • k is in the range [1, the number of unique elements in nums]
  • The answer is guaranteed to be unique.

Input format: First line: space-separated integers. Second line: integer k.

Output format: Space-separated top k frequent elements in ascending order.

Run to check your code against the sample cases, or submit to run every case