Search⌘ K
AI Features

Top K Frequent Elements

Explore methods to identify the top k frequent elements in an integer array. Understand problem constraints, practice implementing solutions, and strengthen your coding interview skills with this key coding pattern.

Statement

Given an array of integers, arr, and an integer, k, return the kk most frequent elements.

Note: You can return the answer in any order.

Constraints:

  • 11 \leq arr.length \leq 10310^{3}
  • 10410^{-4} \leq arr[i] \leq 10410^{4}
  • 1 \leq k \leq number of unique elements in an array.
  • It is guaranteed that the answer is unique.

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Top K Frequent Elements

1.

What is the output if the following inputs are given?

arr = [1, 1, 2, 4, 5, 5]

k = 2

A.

[1]

B.

[5]

C.

[1, 5]

D.

[1, 2]


1 / 2

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground:

JavaScript
usercode > Solution.js
import { MinHeap, MaxHeap } from './Heap.js'
/* The following definition is for MinHeap.
You can use the same methods for MaxHeap.
class MinHeap {
size(); // return number of elements
peek(); // return top element without removing
push(val); // insert element
pop(); // remove and return top element
}
*/
function topKFrequent(arr, k){
// Replace this placeholder return statement with your code
return []
}
export {
topKFrequent
}
Top K Frequent Elements