Question bankPricingSign in

Top K Frequent Elements

Arrays & HashingMedium1:30

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

For example, given nums = [1, 1, 1, 2, 2, 3] and k = 2, the output is [1, 2] because 1 appears 3 times and 2 appears 2 times.

Explain your approach, discuss at least two strategies with different tradeoffs, and analyze time and space complexity.

How to approach it

  • Hint 1

    First, you need to know how many times each element appears. What data structure gives you frequency counts?

  • Hint 2

    Once you have frequencies, you need the top k. A heap of size k avoids sorting all elements.

  • Hint 3

    There is a clever O(n) approach using bucket sort -- the index represents frequency.

Ready to answer it out loud?

Record your answer in 1:30 and Preptile scores it 1–10 with specifics — what landed, what you skipped, and what to say next time.

Practising needs an invite code. Join the waitlist and we’ll send you one.