#347

Top K Frequent Elements

MediumHeapHas vizArrayHash TableHeap
Related studio

Problem

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

Example 1

Input: nums = [1,1,1,2,2,3], k = 2

Output: [1,2]

1 appears 3 times, 2 appears 2 times.

Example 2

Input: nums = [1], k = 1

Output: [1]

Only one element.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is in the range [1, the number of unique elements in the array].
  • It is guaranteed that the answer is unique.
Loading visualization…

Explanation

Top K Frequent Elements is a Medium interview problem tagged [Array, Hash Table, Heap]. The winning approach is typically **Heap**.

Intuition

O(log k) updates beat full sorts when you only need extremes.

Approach

Use a priority queue for Top-K, scheduling, or Dijkstra-style extraction of minima.

  1. Pick min vs max heap polarity.
  2. Push/pop while maintaining size constraints.
  3. Read root as threshold/answer.

Solution

Pattern-level skeleton only — not this problem’s exact answer. Adapt it to the statement.

Pattern templateHeap

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n log n)

Space: O(n)

Before coding, restate the problem, name the pattern (Heap), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #347 Top K Frequent Elements as understood when the pattern clicks.