intermediate · heap · top-k · hashing · frequency count

The k values seen most often

Problem

A sensor reports readings. Return the k distinct readings that occur most often, most frequent first. When two readings occur equally often, the smaller reading ranks higher.

Constraints

  • 1 ≤ n ≤ 32
  • 1 ≤ k ≤ number of distinct readings
  • readings from −999 to 999

Examples

values = [4, 1, 4, 2, 1, 4, 3], k = 2 → [4, 1] — 4 occurs three times, 1 twice.

Show the solution

Count, then a size-k min-heap

The heap is a short list of champions whose weakest member is always at hand. A new candidate either beats that weakest member or is itself the weakest and leaves at once.

Why it is correct

Invariant: after processing some distinct readings, the heap holds the k strongest of them (or all, if fewer). Pushing a new reading and popping the weakest of k + 1 keeps the k strongest of the larger set, since the popped one is beaten by k others. Popping the final heap yields readings weakest first, so reversing gives the required order; ties are broken inside the comparison, so the result is unique.

Complexity

Time O(n + m log k), extra space O(m + k). Counting is O(n) expected. Each of the m distinct readings costs one push and at most one pop on a heap of size ≤ k + 1, O(log k) each.

For contrast: Sort the distinct readings by (count descending, value ascending) and take the first k. That costs O(n + m log m) time and O(m) space.

Edge cases

  • k equal to the number of distinct readings: all of them, ordered.
  • All readings distinct: ties everywhere, decided by value.
  • A single reading.

Common mistakes

  • Using a max-heap of all m readings, which costs O(m log m) and O(m) heap space.
  • Forgetting a tie-break, so different languages return different answers.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class MostFrequentK
{
    /// <summary>The k distinct values that occur most often, most frequent first; ties go to the smaller value. O(n + m log k).</summary>
    public static int[] Find(int[] values, int k)
    {
        var counts = new Dictionary<int, int>();
        foreach (int v in values) counts[v] = counts.GetValueOrDefault(v) + 1;
        // Min-heap: the weakest candidate (fewest occurrences, then the larger value) is on top.
        var heap = new PriorityQueue<int, (int Count, int NegValue)>();
        foreach (var (value, count) in counts)
        {
            heap.Enqueue(value, (count, -value));
            if (heap.Count > k) heap.Dequeue();
        }
        var result = new int[heap.Count];
        for (int i = result.Length - 1; i >= 0; i--) result[i] = heap.Dequeue(); // weakest first, so fill from the back
        return result;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/MostFrequentK.cs

import heapq
from collections import Counter
from collections.abc import Iterable
 
 
def find(values: Iterable[int], k: int) -> list[int]:
    """The k distinct values that occur most often, most frequent first; ties go to the smaller value. O(n + m log k)."""
    counts = Counter(values)
    # Min-heap of (count, -value): the weakest candidate (fewest occurrences, then the larger value) is on top.
    heap: list[tuple[int, int]] = []
    for value, count in counts.items():
        heapq.heappush(heap, (count, -value))
        if len(heap) > k:
            heapq.heappop(heap)
    result = [-heapq.heappop(heap)[1] for _ in range(len(heap))]  # weakest first
    result.reverse()
    return result

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/most_frequent_k.py

package dev.bekadan.dsa.problems;
 
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.PriorityQueue;
 
public final class MostFrequentK {
    private MostFrequentK() {
    }
 
    /** The k distinct values that occur most often, most frequent first; ties go to the smaller value. O(n + m log k). */
    public static int[] find(int[] values, int k) {
        Map<Integer, Integer> counts = new LinkedHashMap<>();
        for (int v : values) {
            counts.merge(v, 1, Integer::sum);
        }
        // Min-heap of {value, count}: the weakest (fewest occurrences, then the larger value) is on top.
        PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[1] != b[1] ? Integer.compare(a[1], b[1]) : Integer.compare(b[0], a[0]));
        for (Map.Entry<Integer, Integer> e : counts.entrySet()) {
            heap.add(new int[] {e.getKey(), e.getValue()});
            if (heap.size() > k) {
                heap.poll();
            }
        }
        int[] result = new int[heap.size()];
        for (int i = result.length - 1; i >= 0; i--) {
            result[i] = heap.poll()[0]; // weakest first, so fill from the back
        }
        return result;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/MostFrequentK.java

#pragma once
 
#include <cstddef>
#include <functional>
#include <map>
#include <queue>
#include <span>
#include <utility>
#include <vector>
 
namespace bekadan::dsa::problems {
 
// The k distinct values that occur most often, most frequent first; ties go to the smaller value. O(n log m + m log k).
inline std::vector<int> most_frequent_k(std::span<const int> values, std::size_t k) {
    std::map<int, int> counts;
    for (const int v : values) ++counts[v];
    // Min-heap of (count, -value): the weakest candidate (fewest occurrences, then the larger value) is on top.
    std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<>> heap;
    for (const auto& [value, count] : counts) {
        heap.emplace(count, -value);
        if (heap.size() > k) heap.pop();
    }
    std::vector<int> result(heap.size());
    for (auto i = result.size(); i-- > 0;) {  // weakest first, so fill from the back
        result[i] = -heap.top().second;
        heap.pop();
    }
    return result;
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/most_frequent_k.hpp