KatInterview

Top-K Labels by Frequency with Alphabetical Tie-Breaking

Heaps, Sorting & SearchAuto-graded · 21 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortinghash-mapheap

Last 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 k distinct 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 in labels.

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).