Top K Frequent Elements

Given an integer array, return the k elements that appear most frequently. To keep the output deterministic, sort by frequency descending and then by element value ascending when frequencies tie.

Input Format

nums = integer array, k = number of frequent elements to return

Output Format

k most frequent values ordered by frequency descending and value ascending on ties

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 1 <= k <= number of distinct values

Examples

Example 1:

Input:

nums = [1,1,1,2,2,3]
k = 2

Output:

[1,2]

Explanation:

1 appears 3 times and 2 appears 2 times.

Example 2:

Input:

nums = [4,1,-1,2,-1,2,3]
k = 2

Output:

[-1,2]

Explanation:

-1 and 2 both appear twice, and -1 comes first on the tie.

Loading...
Top K Frequent Elements - Heap DSA Problem