Solvarch
DSA ProblemsProgressPlanRoadmapsReviewCheat SheetsCompaniesSystem DesignCS FundamentalsQuestion Bank
Theme
Problems

Top K Frequent Elements

Medium
heaphash-tablebucket-sort

Given an integer array nums and an integer k, return the k most frequent values, ordered by frequency (highest first); break frequency ties by smaller value first.

Input

  • Line 1: space-separated integers nums
  • Line 2: integer k

Output: the k values, space-separated.

Example 1
Input:
1 1 1 2 2 3
2
Output:
1 2
Example 2
Input:
4 4 7 7
2
Output:
4 7

Tie on frequency — smaller value first.

Constraints

  • 1 ≤ nums.length ≤ 10^5
  • k is between 1 and the number of distinct values.
Watch a video walkthrough

Run your code against the sample tests, or Submit to run the full suite.