Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Arrays and hashing

The k most frequent values

Medium · Target 15 minutes · Arrays and hashing · Type asked atTwo SigmaCitadelOptiver

Given an array nums and an integer k, return the k values that occur most often. Order them by decreasing frequency; when two values occur equally often, the smaller value comes first.

k is at most the number of distinct values.

Examples

InputOutputWhy
nums = [1, 1, 1, 2, 2, 3], k = 2[1, 2]1 occurs three times, 2 twice.
nums = [4, 4, 4, 6, 6, 6, 5, 5], k = 2[4, 6]4 and 6 tie on three; the smaller goes first.
nums = [9, 8, 7], k = 3[7, 8, 9]Everything ties, so the order is by value.

Constraints

  • 1 ≤ n ≤ 10⁵
  • −10⁴ ≤ nums[i] ≤ 10⁴
  • 1 ≤ k ≤ number of distinct values

Hints

Hint 1

Two separate jobs are hiding in one sentence: counting how often each value appears, and ordering the values by that count.

Hint 2

Counting is one pass with a hash map from value to count. You never need the original order again.

Hint 3

Sort the distinct values by (count descending, value ascending) and take the first k. Then ask whether sorting is the best you can do.

Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.