Katkat

Most Frequent k Words or Bestselling Titles with Alphabetical Tie-Breaks

SnowflakeSoftware Engineer · Technical Screen

Last updated

Given a list of items such as trending words or bestselling book titles and a number k, return the k most frequent items ordered by count, with ties broken alphabetically. It tests frequency counting, sorting with a compound key and heap-based selection.

Given a list of items, such as the words in a stream of text (the hot words) or the book titles in a list of sales (the bestsellers), return the k items that occur most often.

Function Signature

def top_k_frequent(items: list[str], k: int) -> list[str]:

Rules

  • The count of an item is the number of times it appears in items.
  • Return k distinct items ordered from the highest count to the lowest.
  • Items with equal counts are ordered alphabetically, in ascending character order, and that order also decides which items are included when several items tie at the cut-off.

Constraints

  • 1 <= len(items) <= 10^5
  • Every item consists of 1 to 20 lowercase English letters.
  • 1 <= k <= the number of distinct items.

Examples

Example 1

Input: items = ["sql", "rust", "go", "sql", "go", "sql", "java"], k = 2
Output: ["sql", "go"]

sql appears 3 times and go twice; rust and java appear once each.

Example 2

Input: items = ["sql", "rust", "go", "sql", "go", "sql", "java"], k = 3
Output: ["sql", "go", "java"]

java and rust tie with one occurrence each, and java comes first alphabetically.

Example 3

Input: items = ["dune", "emma", "dune", "emma", "ulysses"], k = 1
Output: ["dune"]

dune and emma tie with two occurrences each, and dune comes first alphabetically.