Zero To DSAZero To DSA
Privacy Policy路FAQ路Report a Bug路Support on Ko鈥慺i
Implement Queue Using Stacks

Top K Frequent Elements

medium
Time: O(n log k) using heap, O(n) using bucket sort
Space: O(n + k) using heap, O(n) using bucket sort

Given an integer array nums and an integer k, return the k most frequent elements. (Canonical solution: a min-heap of size k.)

Constraints

  • 1 <= nums.length <= 10^5

Examples

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