MediumArrayHash TableDivide and ConquerSortingHeap (Priority Queue)Bucket SortCountingQuickselect

Top K Frequent Elements

LeetCode
1 approach, code in all languages

You are given an integer array and an integer k. Return the k values that occur most often in the array.

The result may be returned in any order, and the problem guarantees that the set of top-k values is unique. Aim for a solution that is faster than fully sorting the array by frequency.

Example 1

Input: nums = [1,1,1,2,2,3], k = 2

Output: [1,2]

1 appears three times and 2 appears twice, so they are the two most frequent values.

Example 2

Input: nums = [1], k = 1

Output: [1]

There is only one distinct value, and it is the most frequent.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is in the range [1, the number of unique elements in the array]
  • The answer is guaranteed to be unique
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now