← DiffPush

Top K Frequent Elements

DiffPush Tier Heaps · Hard Problems O(n log k) · O(n)

The Frequency Band Charter

A spectrum monitor tallies how often each channel transmitted during a window, and the regulator chart lists the k busiest channels. Ties in traffic share the chart regardless of order, so the monitor only needs the correct set. A small shortlist evicts the quietest channel whenever a busier challenger arrives.

Input: An integer array nums and an integer k.

Output: Return the k most frequent values of nums, in any order.

Constraints

Examples

Example 1

Input: {"nums":[1,1,1,2,2,3],"k":2}
Output: [1,2]
Channel 1 fired three times, channel 2 twice — the two busiest.

Example 2

Input: {"nums":[1],"k":1}
Output: [1]
One channel, one entry on the chart.

Solve this in your browser →

Also on LeetCode ↗