KatInterview

Find Frequent Elements with Custom Tie-Breaking

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searcharrayssortinghash-table

Last updated

Count item occurrences and retrieve the top k highest-frequency elements, sorting tied elements by value ascending.

Given a list of integer identifiers request_ids and an integer k, return a list containing the k most frequent request IDs.

The results must adhere to the following ordering criteria:

  1. Higher frequency items come before lower frequency items.
  2. If two or more request IDs share the same frequency, order them by their numeric ID in ascending order (smaller values first).

If the number of unique IDs in request_ids is less than or equal to k, return all unique IDs ordered by the rules above.

Constraints

  • 0 <= len(request_ids) <= 10^5
  • 1 <= request_ids[i] <= 10^9
  • 1 <= k <= 10^5

Examples

Example 1

Input: top_k_request_ids([101, 202, 101, 303, 202, 101, 404], 2)

Output: [101, 202]

Example 2

Input: top_k_request_ids([500, 300, 500, 300, 200], 5)

Output: [300, 500, 200]

Hints

Hint 1

First, count how many times each distinct ID appears in the input.

Hint 2

To order elements by descending frequency and ascending value, construct a sorting key as a tuple: `(-frequency, id)`.

Hint 3

Python's `sorted()` or `heapq.nsmallest()` can use this tuple key to produce the exact desired ordering.