Given a list of strings tokens and an integer k, return the k most frequent tokens in the list.
The result must be sorted by frequency, highest first. If two tokens have the same frequency, the lexicographically smaller token comes first.
Your implementation should handle large inputs efficiently by avoiding a sort of the entire frequency table when k is small relative to the number of unique tokens.
Function Signature
def top_k_frequent_tokens(tokens: list[str], k: int) -> list[str]:
Rules
-
Lexicographic order is plain string comparison by character code, the same as Python's
<
on
str
. Digits sort before letters, and a token that is a proper prefix of another (
"ab"
and
"abc"
) comes before it.
-
The result contains exactly
k
distinct tokens.
Constraints
-
1 <= len(tokens) <= 10^5
-
1 <= len(tokens[i]) <= 50
-
tokens[i]
consists of lowercase English letters and digits.
-
1 <= k <=
the number of unique tokens in
tokens
.
Examples
Input: tokens = ["apple","banana","apple","cherry","banana","apple"], k = 2
Output: ["apple","banana"]
"apple" appears 3 times, "banana" 2 times and "cherry" once, so the top 2 are "apple" and then "banana".
Input: tokens = ["a","b","c","a","b","a"], k = 1
Output: ["a"]
"a" appears 3 times, more than any other token, so it is the only one returned.
Input: tokens = ["ab","abc","b","abc","ab","b"], k = 2
Output: ["ab","abc"]
All three tokens appear twice, so the tie rule decides. In lexicographic order "ab" comes before "abc" (it is a prefix of it), and "abc" comes before "b", so the first two are kept.