Skip to main content
Abstract Algorithms Logo
Abstract Algorithms
โ† All Problemsยทcoding algorithmMedium~20 min

Top K Frequent Elements

Given an integer array nums and an integer k, return the k most frequent elements. The algorithm's time complexity must be better than O(N log N), where N is the array's size.

Requirements

  • โœ“Return the k most frequent elements in any order.
  • โœ“Time complexity must be strictly better than O(N log N).
  • โœ“Handle negative numbers and arrays with all identical elements.
  • โœ“k is always valid (1 <= k <= number of unique elements).

Constraints & Scale

  • โ€”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.
Understand
Guided mode

Why does full sorting take O(N log N)? What approaches avoid full sorting? Compare min-heap vs bucket sort.

Context & Constraints โ€” Human Reviewed

First pass: frequency map takes O(N) time and O(U) space where U is unique elements. Full sort on frequencies is O(U log U). Min-heap of size k is O(N log k). Bucket sort where index represents frequency is O(N) linear time.

Trade-offs

  • โš–Min-heap: O(N log k) time, O(N) space. Works on streaming data where total size N is unknown ahead of time.
  • โš–Bucket sort: O(N) time, O(N) space. Requires finite bounded frequency space (max frequency is N).

Concepts used in this stage