Tech Interview RoomStudy guides

Heaps & Intervals

Find the top K most frequent elements.

Intermediate · 2 min read · Lesson 1 of 5 in Heaps & Intervals

Problem

Given [1,1,1,2,2,3] and k = 2, return [1, 2].

Approach

  1. Count frequencies with a HashMap: O(n).
  2. Keep a min-heap of size k ordered by frequency: push each entry and pop the smallest when the heap exceeds k. O(n log k), better than sorting everything when k is small.
  3. Alternative: bucket sort by frequency (index = count), O(n).
java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.function.Function;
import java.util.stream.Collectors;

class TopKFrequent {
    static List<Integer> topK(int[] nums, int k) {
        Map<Integer, Integer> freq = new HashMap<>();
        for (int n : nums) freq.merge(n, 1, Integer::sum);

        PriorityQueue<Map.Entry<Integer, Integer>> heap = new PriorityQueue<>(Map.Entry.comparingByValue());
        for (Map.Entry<Integer, Integer> e : freq.entrySet()) {
            heap.offer(e);
            if (heap.size() > k) heap.poll();          // drop the least frequent
        }
        List<Integer> result = new ArrayList<>();
        while (!heap.isEmpty()) result.add(heap.poll().getKey());
        java.util.Collections.reverse(result);         // most frequent first
        return result;
    }

    // Streams version (common in Java 8 interviews), O(n log n)
    static List<String> topKWords(List<String> words, int k) {
        return words.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            .entrySet().stream()
            .sorted(Map.Entry.<String, Long>comparingByValue(Comparator.reverseOrder())
                    .thenComparing(Map.Entry.comparingByKey()))
            .limit(k)
            .map(Map.Entry::getKey)
            .toList();
    }

    public static void main(String[] args) {
        System.out.println(topK(new int[] {1, 1, 1, 2, 2, 3}, 2));                         // [1, 2]
        System.out.println(topKWords(List.of("java", "go", "java", "rust", "go", "java"), 2)); // [java, go]
    }
}

Complexity

Heap: O(n log k) time, O(n) space for counts. Bucket sort: O(n).

Follow-up questions interviewers ask

Try answering each one before you open it.

How would you find top-K over a stream that does not fit in memory?

Exact answers need counts for every distinct item, which may not fit. Use approximate algorithms: Count-Min Sketch with a small heap of candidates, or Space-Saving / Misra-Gries (keep k counters, replacing the minimum), which find heavy hitters with bounded error. In a distributed setting, count per partition and merge, or use a stream processor (Flink) with windowed counts.