Top-K Labels by Frequency with Alphabetical Tie-Breaking
Heaps, Sorting & SearchAuto-graded · 21 test casesLast updated
Tests frequency counting and compound-key sorting to find the k most common strings, resolving ties by alphabetical order for both ranking and inclusion.
You are given a list of string labels and a positive integer k. Return the k labels that appear most often, listed from highest to lowest frequency.
When two or more labels share the same frequency, break the tie by placing them in ascending alphabetical order. This tie-breaking rule applies both to the ordering of results and to which labels are included when a tie falls exactly at the cut-off position.
Function Signature
def top_k_frequent(labels: list[str], k: int) -> list[str]:
Rules
- The frequency of a label is the number of times it appears in
labels. - Return exactly
kdistinct labels, ordered from highest frequency to lowest. - Among labels with equal frequency, use ascending alphabetical order. When multiple labels share the frequency at the boundary, the alphabetically earlier ones take the remaining slots.
Constraints
1 <= len(labels) <= 10^5- Each label consists of 1 to 20 lowercase English letters.
1 <= k <=number of distinct labels inlabels.
Examples
Example 1
Input: top_k_frequent(['sql', 'rust', 'go', 'sql', 'go', 'sql', 'java'], 2)
Output: ['sql', 'go']
Example 2
Input: top_k_frequent(['sql', 'rust', 'go', 'sql', 'go', 'sql', 'java'], 3)
Output: ['sql', 'go', 'java']
Example 3
Input: top_k_frequent(['dune', 'emma', 'dune', 'emma', 'ulysses'], 1)
Output: ['dune']
Hints
Hint 1
Count the frequency of each distinct label first — Python's collections.Counter does this in one pass.
Hint 2
A single sort with a two-component key handles both ordering and tie-breaking at once: negate the count so higher frequencies sort first, then use the label string itself as the second component so ties resolve alphabetically.
Hint 3
Once the distinct labels are sorted by that composite key, the answer is just the first k elements of the sorted list. If k is much smaller than the number of distinct labels, heapq.nsmallest with the same key gives the same result in O(D log k) time instead of O(D log D).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem splits into two straightforward steps: count, then rank.
Step 1 — Count frequencies.
Build a frequency map from the input list. collections.Counter does this in a single pass over labels, hashing each string once.
Step 2 — Sort by a composite key, then slice.
Iterate over the distinct labels (the keys of the counter) and sort them using a two-part key: (-frequency, label).
- Negating the frequency turns a normal ascending sort into a highest-count-first ordering.
- Appending the label string as the second component means that when two labels have identical counts, Python's tuple comparison falls through to lexicographic string comparison, placing the alphabetically earlier label first.
This single key encodes both the ranking rule and the inclusion rule at the boundary. No separate tie-breaking pass is needed — the first k elements of the sorted list are exactly the correct answer.
Why correctness is guaranteed.
Because every label is a distinct string, no two entries in the sorted list can share the same composite key. The ordering is therefore total and deterministic, independent of input order or Python's sort stability. A label beats another if and only if it has a higher count, or the same count and comes earlier alphabetically. Taking the first k elements of this ordering gives precisely the k labels that should be included.
Edge cases worth noting.
- All labels identical:
D = 1,k = 1, trivially returns that one label. - All labels distinct: every frequency is 1, so the result is the
kalphabetically smallest labels. - Tie at the cut-off (e.g., two labels share frequency 2 and
k = 1): only the alphabetically earlier one is returned, which the composite key handles automatically.
Complexity.
Let N = len(labels), D = number of distinct labels, and L ≤ 20 = maximum label length.
- Time:
O(N·L)for counting (each label is hashed once) +O(D·L·log D)for sorting (each comparison touches up toLcharacters). WithLfixed at 20, this is effectivelyO(N + D log D). - Space:
O(D·L)for the counter and the sorted list of distinct labels.
Heap variant for small k.
When k is much smaller than D, you can replace the full sort with:
heapq.nsmallest(k, cnt, key=lambda w: (-cnt[w], w))
This runs in O(D log k) time using the same composite key, producing the same result in the same order.
Reference Solution
from collections import Counter
from typing import List
def top_k_frequent(labels: List[str], k: int) -> List[str]:
cnt = Counter(labels)
return sorted(cnt, key=lambda w: (-cnt[w], w))[:k]