मुख्य कंटेंट तक स्किप करें
Back to ChallengesTop K Frequent ElementsHard 40 min

Top K Frequent Elements

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

Examples

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
1 appears three times, 2 appears two times.

Constraints

  • 1 <= nums.length <= 10^5
  • k is in the range [1, the number of unique elements in the array].
  • It is guaranteed that the answer is unique.

Complexity Analysis

Time
O(N)
using Bucket Sort (array as frequencies).
Space
O(N)
hash map and buckets array.

Test Cases

#1 Standard case
Input: nums = [1,1,1,2,2,3], k = 2
Expected: [1,2]
#2 Single element
Input: nums = [1], k = 1
Expected: [1]
JavaScript
Output
Click "Run Code" to see output here...