Blind 75
5 / 75Free practice

Top K Frequent Elements

Medium · Arrays & hashing

Jump to code

Return the k most frequent distinct integers in a nonempty array. Assume 1 ≤ k ≤ the number of distinct values and that the top-k set is unique. Order does not matter.

Examples

Example 1

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

Output: [1,2]

Example 2

nums = [1]
k = 1

Output: [1]

Constraints

  • 1 <= nums.length <= 10^4.
  • -1000 <= nums[i] <= 1000
  • 1 <= k <= number of distinct elements in nums.
Need a hint?

No frequency can exceed the array length.

Asked in real interviews

Candidates reported versions of Top K Frequent Elements from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 9 cases. No account or XP needed for this problem.
Language
Case 1
Input
[
  [
    1,
    1,
    1,
    2,
    2,
    3
  ],
  2
]
Expected
[
  1,
  2
]
Case 2
Input
[
  [
    1
  ],
  1
]
Expected
[
  1
]
Case 3
Input
[
  [
    4,
    4,
    4,
    6,
    6,
    7
  ],
  1
]
Expected
[
  4
]
Case 4
Input
[
  [
    1,
    2,
    2,
    3,
    3,
    3
  ],
  2
]
Expected
[
  3,
  2
]
Case 5
Input
[
  [
    0,
    0,
    0,
    1,
    2,
    2
  ],
  2
]
Expected
[
  0,
  2
]

Drafts are saved per language in this browser when storage is available.