Skip to main content
LeetCode 347, Medium. Topics: Array, Hash Table, Divide and Conquer, Sorting, Heap (Priority Queue), Bucket Sort, Counting, Quickselect. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 13 parametrized pytest cases, and a playground notebook:

Problem

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

Examples

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].
  • It is guaranteed that the answer is unique.
Follow up: Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Blind 75, NeetCode 150, NeetCode 250, NeetCode All, AlgoMaster 75.
Last modified on August 25, 2026