FastPrepMost-Frequent Next-Word Predictor

Most-Frequent Next-Word Predictor

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

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.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public String[] predictNextWords(String[] trainingTokens, String[] queries) {
    // Write your code here
}
trainingTokens["i","like","tea","i","like","coffee","i","like","tea"]
queries["i","like"]
expected["like", "tea"]
Checking account…