CodingNodes / Arrays & Hashing / Top K Frequent Elements System design Space play · ←→ step · R restart

Problem

Given an integer array nums and an integer k, return the k values that appear most often in nums. The answer may be in any order.

The tests are built so the answer is unique: there is no tie for the last place. Aim for a running time better than O(n log n).

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • −10⁴ ≤ nums[i] ≤ 10⁴
  • 1 ≤ k ≤ the number of distinct values in nums
  • The set of the k most frequent values is unique

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: One pass to count, one to fill buckets, and one walk over at most n + 1 buckets that touches each value once.

Space: The count map holds up to n distinct values, and the n + 1 buckets together hold those same values.

Count each value with a hash map. A value can appear at most n times, so file every value into the bucket numbered by its count. Walk the buckets from the highest count down and collect values until you have k. No sorting needed.