FastPrepWeighted Next-Word Prediction From Training Sequences

Weighted Next-Word Prediction From Training Sequences

Google logoGoogle● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

sentences contains training word sequences. Every adjacent pair contributes one observed transition from the first word to the second.

Given currentWord, count how often each word immediately follows it. Sort candidate next words lexicographically and lay out one ticket for every observed occurrence. ticket is a zero-based index into those weighted tickets.

Return the candidate owning that ticket. Return the empty string when currentWord has no observed successor. In that case ticket is 0.

Function

predictNextWord(sentences: String[][], currentWord: String, ticket: int) → String

Examples

Example 1

sentences = [["a","b","c"],["a","s","d"]]currentWord = "a"ticket = 0return = "b"

b and s each follow a once; lexicographic weighted tickets are [b,s].

Example 2

sentences = [["a","b"],["a","b"],["a","c"]]currentWord = "a"ticket = 1return = "b"

The tickets are [b,b,c], so ticket 1 still selects b.

Example 3

sentences = [["a","b"],["c"]]currentWord = "b"ticket = 0return = ""

b never appears before another word.

Constraints

  • 0 <= sentences.length <= 100000.
  • The total number of words is at most 500000.
  • Words contain lowercase English letters and have length from 1 through 50.
  • If successors exist, 0 <= ticket < total successor occurrences; otherwise ticket == 0.

More Google problems

See Google hiring insights
public String predictNextWord(String[][] sentences, String currentWord, int ticket) {
    // write your code here
}
sentences[["a","b","c"],["a","s","d"]]
currentWord"a"
ticket0
expected"b"
Checking account…