Facebook PixelTop K Frequent Elements — Coding Practice
Top K Frequent ElementsMedium

Top K Frequent Elements

Medium 16.8k63% acceptance
ArrayHash TableHeapBucket Sort

Given an integer array nums and an integer k, return the k most frequent elements.

Output ordering (required): return the k elements sorted in ascending order so the result is unambiguous. The test inputs guarantee the set of top-k elements is unique (no frequency tie spans the cutoff).

Example 1
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
1 appears 3 times and 2 appears twice — the two most frequent, returned in ascending order.
Example 2
Input: nums = [4,4,5,5,5,1], k = 1
Output: [5]
Example 3
Input: nums = [7], k = 1
Output: [7]
Constraints
  • 1 ≤ nums.length ≤ 100000
  • -10000 ≤ nums[i] ≤ 10000
  • 1 ≤ k ≤ number of distinct elements in nums.
  • The top-k set is uniquely determined.
Asked atAmazonGoogleMetaMicrosoftApple
JavaScript
Loading editor…
Case 1
[1,1,1,2,2,3], 2
expected: [1,2]
Case 2
[4,4,5,5,5,1], 1
expected: [5]
Case 3
[7], 1
expected: [7]
Case 4
[1,2,3,4,5], 5
expected: [1,2,3,4,5]
Case 5
[-1,-1,-2,-2,-2,3], 2
expected: [-2,-1]
Case 6
[5,5,4,4,4,3,3,3,3,2], 3
expected: [3,4,5]
Case 7
[10,10,10,9,9,8], 2
expected: [9,10]