Top K Frequent Values

Quick Overview

Return the top k most frequent integers with a deterministic smaller-value tie-break and efficient frequency selection.

Top K Frequent Values

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

# Top K Frequent Values Implement `top_k_frequent(values: list[int], k: int) -> list[int]`. Return the `k` distinct integers that occur most frequently in `values`. ### Input Domain - `1 <= len(values) <= 200,000`. - Every value fits in a signed 32-bit integer. - `1 <= k <=` the number of distinct values. ### Output Rules - Sort the result by descending frequency. - When two values have the same frequency, place the smaller integer first. - Return exactly `k` values and no duplicates. - The input list must not be modified. ### Constraints - Target time is `O(n log k)` or `O(n)` after frequency counting. - Additional space may be proportional to the number of distinct values. ### Examples #### Example 1 Input: `values = [1,1,1,2,2,3], k = 2` Output: `[1,2]` #### Example 2 Input: `values = [4,4,5,5,6,6], k = 2` Output: `[4,5]` ```hint Make ties part of ranking Treat each candidate as a pair of frequency and value so the same comparison controls selection and final ordering. ```

Quick Answer: Return the top k most frequent integers with a deterministic smaller-value tie-break and efficient frequency selection.

|Home/Coding & Algorithms/Amazon
Amazon logo
Amazon
Sep 2, 2026
mediumSoftware EngineerTechnical ScreenCoding & Algorithms
8
0

Top K Frequent Values

Implement top_k_frequent(values: list[int], k: int) -> list[int].

Return the k distinct integers that occur most frequently in values.

Input Domain

  • 1 <= len(values) <= 200,000 .
  • Every value fits in a signed 32-bit integer.
  • 1 <= k <= the number of distinct values.

Output Rules

  • Sort the result by descending frequency.
  • When two values have the same frequency, place the smaller integer first.
  • Return exactly k values and no duplicates.
  • The input list must not be modified.

Constraints

  • Target time is O(n log k) or O(n) after frequency counting.
  • Additional space may be proportional to the number of distinct values.

Examples

Example 1

Input: values = [1,1,1,2,2,3], k = 2

Output: [1,2]

Example 2

Input: values = [4,4,5,5,6,6], k = 2

Output: [4,5]

Submit Your Answer to Earn 20XP

Sign in to leave a comment

Loading comments...