‹ DS&A interview · Socratic
DSA · Heap / bucket sort · #07

Top K Frequent Elements

Module 9 · difficulty 3/5·30:00starts on first keystroke

Given an integer array `nums` and an integer `k`, return the `k` most frequent elements. You may return the answer in any order. If two elements tie at the kth boundary, the spec is ambiguous — confirm during phase A.

Examples
  • nums = [1,1,1,2,2,3], k = 2 [1,2]
  • nums = [1], k = 1 [1]
  • nums = [4,4,4,5,5,6], k = 3 [4,5,6]k == number of distinct values

Stuck? Reveal an animated walkthrough of the approach.

Constraints
  • · 1 <= nums.length <= 10^5
  • · -10^4 <= nums[i] <= 10^4
  • · k is in the range [1, number of unique elements].
  • · It is guaranteed that the answer is unique.
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.