Google questions

Next Word Predictor

GoogleOnsiteMedium

Each test creates one Predictor instance and calls its methods in order. The output lists every method call's return value; calls that return None record null.

Part 1: Most frequent next word

You are building a word predictor that learns from sequences of words.

train(words) counts, for every pair of adjacent words in words, how many times the second word immediately follows the first. Pairs never span two train calls: the last word of one call is not followed by the first word of the next.

predict(word) returns the word that most often followed word, or None if word has never been followed by anything. When several words tie on count, return the one that first appeared after word earliest across all training.

predict is called far more often than train, so a predict call should take constant time on average.

  1. Example 1
    init
    []
    operations
    [["train",[["go","left","go","right","go","left"]]],["predict",["go"]],["predict",["left"]],["predict",["right"]],["predict",["stop"]],["train",[["go","right"]]],["predict",["go"]]]
    Output
    [null,"left","go","go",null,null,"left"]

    Why: After the first sequence, go is followed by left twice and right once, so predict(go) is left. Both left and right are followed by go once. The last train call raises right to 2, tying with left; left followed go first, so predict(go) stays left. A word never seen as a predecessor, like stop, gives None.

Constraints

  • 1 <= len(operations) <= 10^5
  • 1 <= len(words) <= 10^4 for each train call
  • 1 <= len(word) <= 10
  • 'a' <= word[i] <= 'z'
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question