← Questions
Next-word predictor from bigram counts
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's onsite coding round, last asked Feb 2026. It tests hash maps, sampling and nlp.
Build a next-word predictor from training sentences, each a list of words, for example [["a", "b", "c"], ["a", "s", "d"]]. Learn which words follow each word and how often, then predict the word that comes next.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
Predictor(sentences: list[list[str]])— counts, for every word, the words that directly follow it inside a sentence. -
predict(word: str) -> str | None— the most frequent follower; ties broken by a rule you state (here, the word seen first);Nonewhen the word was never followed by anything. -
sample(word: str) -> str | None— a follower drawn at random with probability proportional to its count.
Example
sentences = [["a", "b", "c"], ["a", "s", "d"], ["a", "b", "d"]]
counts after "a": {"b": 2, "s": 1}
predict("a") -> "b"
predict("d") -> None # "d" only ends sentences
sample("a") -> "b" with probability 2/3, "s" with probability 1/3
Constraints
- Up to 10^7 words of training text; the vocabulary can be in the millions.
-
predictis called far more often than training happens.
Clarifying questions
- Do pairs cross sentence boundaries?
- How are ties broken in
predict? - Is the text normalized (case, punctuation)?
- Must
samplebe reproducible in tests (an injectable random generator)?
What a strong answer covers
- A map from word to a counter of followers; O(total words) to build.
- Precomputing the best follower per word so
predictis O(1). - Weighted sampling: prefix sums of counts plus binary search, O(log m) per call, or the alias method for O(1).
- Memory at scale: pruning rare pairs, keeping only the top few followers per word, integer word ids instead of strings, or approximate counting.
- Tests: unseen words, a word that only ends sentences, ties.
Follow-ups
- New sentences keep arriving: update counts and the best follower incrementally.
- Use the previous two words (trigrams), and back off to bigrams when a pair is unseen.
- Predict the top three next words for an autocomplete box.
Where it's asked
- Google · Onsite coding · Last asked Feb 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)
What it tests
hash maps · sampling · nlp
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
