DIY: Top K Frequent Elements
Solve the interview question "Top K Frequent Elements" in this lesson.
We'll cover the following
Problem statement
You are provided with an array of integers. Return the k
most frequent elements.
Input
The input will be a list of integers. The following is an example input:
nums = [1, 3, 5, 14, 18, 14, 5]
k = 2
Output
The output will be a list of the top k
frequent numbers. For the above input, the output will be:
[5, 14]
Coding exercise
For this coding exercise, you need to implement the topKFrequent(nums, k)
function, where nums
is the list of integers and k
is the number of frequent elements that need to be returned. The function should return a list of the top k
frequent numbers.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.