Hack Frontend Community

K Most Frequent Elements

YandexTinkoffAvito
Write a function that takes an array of integers nums and an integer k, and returns an array of the k most frequently occurring elements. Conditions:
  • - If k is greater than the number of unique elements in the array, return all unique elements.

Examples:

Input 1: [1, 1, 1, 2, 2, 3], 2
Output 1: [1, 2]
Input 2: [1, 2, 3, 4, 5], 2
Output 2: [1, 2]
Run your code to see results.