LeetCode 347 Top K Frequent Elements - Problem Statement

The problem

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

For example, nums = [1, 1, 1, 2, 2, 3] with k = 2 returns [1, 2]. Element 1 appears 33 times, 2 appears twice. Those are the top 22 by frequency.

Think about how you'd count frequencies first. Then ask: how do you efficiently find the top k without sorting all elements?

Constraints: 1n1051 \le n \le 10^5, kk is always valid (at most the number of unique elements).