Chaturmind
LearnDSASystem DesignBlogPremium
Sign inGet started
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML

Company

  • Blog
  • Premium
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.

DSA›HEAP›Top K Frequent Elements
Medium

Top K Frequent Elements

heaphash-mapbucket-sort

Problem

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

Examples

Example 1

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

Output: [1,2]

Constraints

  • •1 <= nums.length <= 10^5
  • •k is in the range [1, the number of unique elements in the array].

Hints

Hint 1

Min-heap of size k: maintain the k most frequent elements.

Solutions

public int[] topKFrequent(int[] nums, int k) {
    Map<Integer, Integer> freq = new HashMap<>();
    for (int n : nums) freq.merge(n, 1, Integer::sum);

    // Min-heap by frequency — keeps only the k most frequent
    PriorityQueue<Integer> minHeap =
        new PriorityQueue<>(Comparator.comparingInt(freq::get));

    for (int num : freq.keySet()) {
        minHeap.offer(num);
        if (minHeap.size() > k) minHeap.poll(); // remove least frequent
    }
    return minHeap.stream().mapToInt(i -> i).toArray();
}
Java

Time: O(n log k) · Space: O(n)