You are given a list of log entries logs, where each entry is a string of lowercase words separated by spaces, and an integer k. Return the k most frequent words across all log entries.
Order the result by frequency, highest first. When two words have the same frequency, the word that comes first in lexicographic order goes first.
Function Signature
def top_k_frequent_words(logs: list[str], k: int) -> list[str]:
Rules
-
Every occurrence of a word counts, including repeats inside the same entry.
-
Sort by frequency in descending order. Break ties by comparing the words lexicographically in ascending order.
-
Return exactly
k
words.
Constraints
-
1 <= len(logs) <= 10^4
-
1 <= len(logs[i]) <= 100
-
1 <= k <=
the number of distinct words in
logs
-
Each entry in
logs
is a non-empty string of space-separated lowercase words.
Examples
Input: logs = ["the quick brown fox", "the lazy dog", "the quick fox"], k = 2
Output: ["the", "fox"]
"the" appears 3 times. "quick" and "fox" appear twice each, and "fox" comes before "quick" lexicographically, so it takes the second slot.
Input: logs = ["apple banana apple", "banana cherry", "apple cherry cherry"], k = 3
Output: ["apple", "cherry", "banana"]
"apple" and "cherry" each appear 3 times (repeats within one entry count), so they come first in alphabetical order. "banana" follows with 2.
Input: logs = ["dog cat", "bird"], k = 2
Output: ["bird", "cat"]
Every word appears once, so the order is purely lexicographic and the first two words are "bird" and "cat".