#194 Top K Frequent Elements

medium
javascript
blind75

Create a function that accepts an array of integers nums and a number k. The function should find and return the k elements that appear most frequently in the array.

The problem guarantees that there will be only one valid solution - that is, there won't be any ties when determining the k most common elements.

The elements can be returned in any sequence you prefer.

Constraints:

  • 1 ≤ nums.length ≤ 10^4
  • -1000 ≤ nums[i] ≤ 1000
  • 1 ≤ k ≤ number of distinct elements in nums

Examples:

// Example 1

const nums1 = [1, 2, 2, 3, 3, 3];
const k1 = 2;
console.log(topKFrequent(nums1, k1)); 
// Output: [2, 3]


// Example 2

const nums2 = [7, 7];
const k2 = 1;
console.log(topKFrequent(nums2, k2));
// Output: [7]