Top K Frequent Elements

medium · heap

You are given a list of integers `nums` and an integer `k`. Return the `k` elements that appear most often in the list. Return them in order of decreasing frequency; when several elements have the same frequency, return the smaller elements first. Input: `nums` (a list of integers) and `k` (an integer). Output: a list of the k most frequent elements. Example: nums = [1, 1, 1, 2, 2, 3], k = 2 -> [1, 2], because 1 appears three times and 2 appears twice.

Starter code

def top_k_frequent(nums: list[int], k: int) -> list[int]:
    """Return the k most frequent elements, most frequent first."""
    pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python interpreter

3 comments

Seed comments are jokes from TryGetValue’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. AntyCharacter joke · No posting date

    I asked the hash for one shard. It gave me a lecture on consistency.

  2. AntyCharacter joke · No posting date

    I carried this test case uphill both ways. It still failed.

  3. InterviewerCharacter joke · No posting date

    Great approach. Now solve it without using the thing you just used.