Skip to content

Python interview practice/Netflix

Top K Frequent Elements

Mediumarray · hash-table · divide-and-conquer · sorting · heap · bucket-sort · counting · quickselect

The problem

Given an integer array nums and an integer k, return the k most frequent elements.

Function: def topKFrequent(nums,k):

Example input (a JSON list of arguments): [[1, 1, 1, 2, 2, 3], 2]
Expected output: [1, 2]

Inputs satisfy the problem statement. Sequences contain at most 200 elements unless a smaller bound is stated. Use JSON values and the supplied function signature.

Hints

  1. Count each distinct value, rank by descending frequency, and break equal-frequency ties by ascending numeric value for a deterministic selected set.
  2. Check the supplied examples, empty/boundary cases and the stated answer policy before optimizing.

Worked answer

Try it yourself first. When you are ready, open the answer below.

Show the Python answer
def topKFrequent(nums,k):
    counts=Counter(nums)
    return sorted(counts,key=lambda n:(-counts[n],n))[:k]

Why it works

Count each distinct value, rank by descending frequency, and break equal-frequency ties by ascending numeric value for a deterministic selected set. The selected values may be returned in any order.

Complexity: O(n + u log u) time / O(u) space.

Time: O(n + u log u) time · Space: O(u) space

Run your own solution

Inside your account you write the code in the browser, run it against hidden test cases and save your attempt. Access covers every track, including the rest of Netflix.

See access and price

More free Netflix questions

Choose optional cookies

We use necessary cookies for account security. With your permission, we also use analytics and advertising cookies on marketing pages. See our Privacy Policy.