KatInterview

Most Common Values with First-Seen Tie-Breaking

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashinghash-mapbucket-sortfrequency-count

Last updated

Return the k most frequent values in an integer list, ordered by count and then by first appearance, using hash counting and frequency buckets for linear time.

You are given a list of integers values and a positive integer k. Return the k values that occur most often in values, as a list in a specific order.

Ordering rules

The returned list must follow these rules exactly:

  1. Values with a higher number of occurrences come first.
  2. If two values occur the same number of times, the one whose first occurrence in values has the smaller index comes first.

Each distinct value appears at most once in the output, and the output has exactly k elements.

Goal

Aim for an average-case running time of O(n) and O(n) extra space, where n is the length of values. Think about how the possible frequencies are bounded, and how you can group values by frequency without a comparison sort.

Constraints

  • 1 <= len(values)
  • Values may be negative, zero, or positive, and may span a very large range, so do not index arrays by value.
  • 1 <= k <= number of distinct values in values
  • The output is a list of k integers ordered as described above.

Examples

Example 1

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

Output: [1, 2]

Example 2

Input: most_common_values([4, 4, -1, -1, -1, 2, 2, 3], 2)

Output: [-1, 4]

Example 3

Input: most_common_values([5], 1)

Output: [5]

Hints

Hint 1

Count how often each value occurs with a hash map, and remember the order in which distinct values were first seen.

Hint 2

No value can occur more than n times, so you can create buckets indexed by frequency (0 to n) instead of sorting.

Hint 3

Place each distinct value in the bucket for its count, in first-seen order, then scan buckets from highest frequency to lowest and stop once you have k values.