Most-Frequent Next-Word Predictor
Problem statement
Train a next-word predictor from one ordered array of case-sensitive tokens. Every adjacent pair contributes one observation from its first token to its second.
For each query token, return the observed following token with highest frequency. Break frequency ties by lexicographically smaller token. Return the empty string when the query has no observed successor. Precompute the winning successor while processing the training data so each query is answered in average O(1) time.
Function
predictNextWords(trainingTokens: String[], queries: String[]) → String[]Examples
Example 1
trainingTokens = ["i","like","tea","i","like","coffee","i","like","tea"]queries = ["i","like"]return = ["like","tea"]The word after i is always like, while tea follows like twice and coffee once.
Example 2
trainingTokens = ["x","z","x","a"]queries = ["x"]return = ["a"]The successors a and z tie, so the lexicographically smaller a wins.
Constraints
1 <= trainingTokens.length, queries.length <= 200000- Every token is a nonempty printable ASCII string of length at most
40. - The total number of token characters across both arrays is at most
1000000.