KatInterview

Select the k Most Common Values with Tie Rules

Heaps, Sorting & SearchAuto-graded · 20 test cases
MediumAuto-gradedHeaps, Sorting & Searchheaphash-mapfrequency-counting

Last updated

Count value frequencies and pick the k most frequent values, using a bounded heap and a defined tie-break rule for equal counts.

You are given a list of integers values and a non-negative integer k. Return the k values that occur most often in the list.

Selection rule

Rank the distinct values by the pair (count, value), where count is the number of times the value appears. A higher count ranks higher. If two values have the same count, the larger value ranks higher. Return the k highest-ranked distinct values.

This rule makes the chosen set unique. For example, if only one slot remains and 3 and 4 both appear once, 4 is chosen.

Output

  • Return a list of the selected values.
  • The order of the values inside the returned list is not significant.
  • If k is 0 or the input is empty, return an empty list.
  • If k is at least the number of distinct values, return every distinct value.
  • Negative numbers are ordinary values and need no special handling.

Constraints

  • values contains integers, possibly negative and possibly repeated. It may be empty.
  • k >= 0, and k may be larger than the number of distinct values.
  • Aim for roughly O(n + m log k) time, where n = len(values) and m is the number of distinct values, and avoid sorting all distinct values when k is small.

Examples

Example 1

Input: select_top_frequent([1, 1, 1, 2, 2, 3], 2)

Output: [2, 1]

Example 2

Input: select_top_frequent([4, 4, -1, -1, -1, 2, 2, 2, 2], 2)

Output: [-1, 2]

Example 3

Input: select_top_frequent([5], 1)

Output: [5]

Example 4

Input: select_top_frequent([1, 2, 3, 4], 2)

Output: [3, 4]

Hints

Hint 1

Start by counting how often each value appears with a hash map. After that, you only need to deal with the distinct values.

Hint 2

You don't need to sort all distinct values. Keep a min-heap of at most k candidates keyed by (count, value) and evict the smallest whenever it grows beyond k.

Hint 3

Tuples compare lexicographically, so (count, value) in a min-heap already evicts the lower count first and, on equal counts, the smaller value. This gives the required tie rule. Check k = 0 and k larger than the number of distinct values.