#347 Top K Frequent Elements

MediumArrays & Hashing~20 min

Given an integer array nums and an integer k, return the k values that occur most often in the array. The answer may be returned in any order, and you can assume it's unique. No ties force a choice between two equally frequent values for the last slot.

Examples

Inputnums = [1, 1, 1, 2, 2, 3], k = 2
Output[1, 2]

1 appears three times and 2 appears twice; 3's single appearance loses.

Inputnums = [1], k = 1
Output[1]

One element, one winner.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • 1 ≤ k ≤ number of distinct elements
  • The answer is guaranteed to be unique

The explainer is the good part.

Sign in for the full intuition build-up, every approach from naive to optimal with complexity analysis, progressive hints, and commented solutions in Python, JavaScript, and Java. All free.

Want a taste first? Try a free sample: Two Sum or Valid Parentheses.