Zero To DSAZero To DSA
Privacy Policy
Implement Queue Using Stacks

Top K Frequent Elements (Heap)

medium
Time: O(n log k)
Space: O(n + k)

Given an integer array `nums` and an integer `k`, return the k most frequent elements using a heap/priority queue.

Constraints

  • 1 <= nums.length <= 10⁵

Examples

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