Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the top k frequent elements

Return the k most frequent elements from an integer array using hashing and sorting for determinism.

Python practice15 minHashing & SetsIntermediateLast updated March 26, 2026

Problem statement

Given a non-empty list of integers nums and an integer k, return a list of the k most frequent elements. If multiple elements have the same frequency, break ties by choosing the smaller numeric value first. The result should be ordered by descending frequency (highest frequency first) and then by ascending numeric value for ties.

Task

Use a frequency map to identify and return the k elements with highest frequency (tie-broken deterministically).

Examples

Basic example

Input

nums = [1,1,1,2,2,3], k = 2

Output

[1, 2]

1 appears 3 times, 2 appears 2 times, 3 appears once. The top 2 are [1, 2].

Input format

A list of integers nums and an integer k.

Output format

A list of k integers sorted by descending frequency and tie-broken by ascending value.

Constraints

1 <= k <= number of unique elements in nums; nums length >= 1; elements fit in 32-bit signed int.

Samples

Sample 1

Input

nums = [4,4,4,6,6,5,5,5], k = 2

Output

[4, 5]

4 and 5 both appear 3 times; tie broken by smaller value first (4 then 5).