Top K Frequent Elements

Medium#347k largest

You get an array of integers and a number k. Return the k numbers that appear most often, in any order; the answer is always unique. Our example: [9, 1, 9, 4, 1, 4, 1, 4] and k = 2 — the answer is [4, 1]: 4 and 1 appear 3 times each, 9 only twice.

input
nums: integers, with repeats; k: how many numbers to return.
returns
The k numbers that appear in nums most often, in any order. The answer is always unique. LeetCode wants it faster than O(n log n).
constraints
  • 1 ≤ nums.length ≤ 10⁴
  • −10⁴ ≤ nums[i] ≤ 10⁴
  • 1 ≤ k ≤ the number of different numbers in nums
  • the answer is unique
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
function topKFrequent(nums, k) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more heap and top k problems

Pattern “Heap and top K” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.