Skip to content
MediumHeapFree practice

Top K Frequent Elements

Asked atamazonmetagoogleapplemicrosoftbloombergoracleuber

01 · Problem

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

It is guaranteed that the answer is unique.

02 · Examples

Example 01
Input
nums = [1,1,1,2,2,3], k = 2
Output
[1,2]

1 appears 3 times and 2 appears 2 times. The two most frequent elements are 1 and 2.

Example 02
Input
nums = [1], k = 1
Output
[1]

There is only one element, so it is the most frequent.

Example 03
Input
nums = [4,4,4,1,1,2,2,2,3], k = 2
Output
[4,2]

4 appears 3 times and 2 appears 3 times. Both are among the top 2 most frequent.

03 · Constraints

  • 011 <= nums.length <= 105
  • 02-104 <= nums[i] <= 104
  • 03k is in the range [1, the number of unique elements in the array]
  • 04It is guaranteed that the answer is unique

04 · Optimal complexity

Time
O(n)
Space
O(n)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.