Find Frequent Elements with Custom Tie-Breaking
Heaps, Sorting & SearchAuto-graded · 22 test casesLast 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:
- Higher frequency items come before lower frequency items.
- 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^51 <= request_ids[i] <= 10^91 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires aggregating occurrence counts for each unique ID and extracting the top $k$ items under a specific multi-level sorting rule.
- Tally Frequencies: We iterate through
request_idsusing a hash map (or standardcollections.Counterin Python) to compute the count of each distinct ID. - Sort with Composite Keys: We sort the unique keys according to the criteria:
- Primary criterion: Frequency descending. By negating the count (
-counts[x]), standard ascending tuple comparison ranks larger counts earlier. - Secondary criterion: ID value ascending (
x).
- Primary criterion: Frequency descending. By negating the count (
- Slice Top Results: Slicing the sorted keys to index
kyields the desired result. Slicing safely handles cases where $k$ exceeds the total number of unique elements without requiring extra conditional logic.
Alternatively, heapq.nsmallest(k, counts, key=lambda x: (-counts[x], x)) can be used to select the top $k$ directly in $O(U \log k)$ time, where $U$ is the number of distinct IDs.
Complexity Analysis
- Time Complexity: $O(N + U \log U)$ where $N$ is the length of
request_idsand $U$ is the number of distinct elements ($U \le N$). Counting takes $O(N)$ time and sorting $U$ unique elements takes $O(U \log U)$ time. (Using a min-heap reduces this to $O(N + U \log k)$). - Space Complexity: $O(U)$ to store the frequency map and the unique key list.
Python Reference Solution
from collections import Counter
from typing import List
def top_k_request_ids(request_ids: List[int], k: int) -> List[int]:
# Compute frequency of each unique identifier
counts = Counter(request_ids)
# Sort distinct IDs: primary key is -frequency (descending), secondary key is ID (ascending)
ranked = sorted(counts, key=lambda x: (-counts[x], x))
# Return the first k elements
return ranked[:k]