Most Likely Follower Lookup Over Streaming Sentences
Data Structure DesignAuto-graded · 20 test casesLast updated
Process a stream of add and query operations over sentences, tracking adjacent-word counts and returning the most frequent follower with lexicographic tie-breaking.
You are building a tiny autocomplete engine that suggests which word most often comes right after a given word. The engine is driven by a sequence of operations that is replayed against it.
Task
Write a function that simulates the engine. You receive two parallel lists, operations and arguments. The i-th entry of operations names an operation, and the i-th entry of arguments is the list of arguments for that operation. The engine starts empty.
Two operations exist:
"add_sentences": its argument list holds one item, a list of sentence strings. Split each sentence on whitespace to get its words. For every pair of neighbouring words(left, right)inside the same sentence, record thatrightfollowedleftonce. Pairs never span two different sentences. This operation producesNonein the output."get_next_word": its argument list holds one item, a stringword. The result is the word that has followedwordthe most times across all sentences added so far. If several words are tied for the highest count, return the lexicographically smallest of them. Ifwordhas never been followed by any word (it was never seen, or it only ever appeared as the last word of a sentence, or only in single-word sentences), the result isNone.
Return a list with one entry per operation, in order: None for each "add_sentences", and the answer for each "get_next_word".
Details
- Words are compared exactly, so
"Cat"and"cat"are different words. - Splitting uses any run of whitespace as a separator, and leading or trailing whitespace is ignored. Empty sentences and one-word sentences contribute no pairs.
- A word can follow itself (for example
"go go"recordsgofollowed bygo). - Counts accumulate across multiple
"add_sentences"calls, and a query reflects everything added before it. - Lexicographic order is the standard string order of Python.
- Queries may be frequent, so aim for fast lookups.
Constraints
- The total number of words across all sentences is at most 10^5.
operationsandargumentshave the same length.- Each operation is either
"add_sentences"or"get_next_word". - Words are non-empty strings without internal whitespace.
Examples
Example 1
Input: simulate_follower_engine(['add_sentences', 'get_next_word', 'get_next_word', 'get_next_word'], [[['cat sat on mat', 'cat sat on rug', 'dog sat on mat']], ['cat'], ['sat'], ['on']])
Output: [None, 'sat', 'on', 'mat']
Example 2
Input: simulate_follower_engine(['add_sentences', 'get_next_word', 'get_next_word', 'get_next_word', 'get_next_word'], [[['a b c', 'a b d', 'a b d', 'x y']], ['a'], ['b'], ['c'], ['z']])
Output: [None, 'b', 'd', None, None]
Example 3
Input: simulate_follower_engine(['add_sentences', 'get_next_word', 'add_sentences', 'get_next_word'], [[['one two']], ['one'], [['one three', 'one three']], ['one']])
Output: [None, 'two', None, 'three']
Hints
Hint 1
Only adjacent words inside a single sentence count; build pairs per sentence so the end of one sentence is never linked to the start of the next.
Hint 2
Keep a nested map from a word to a map of follower counts. A query that rescans all followers can be slow if queries are frequent.
Hint 3
Because counts only ever increase, you can maintain the current best follower for each word as you add pairs: after incrementing a pair, compare the follower against the stored best by (higher count, then smaller word).
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Do the work when data is added so that each query is a single dictionary lookup.
We keep two structures:
counts[left][right]: how many timesrightimmediately followedleft.best[left]: the current answer forleft, i.e. the follower with the highest count, with the lexicographically smaller word winning ties.
For each sentence, split it into words and walk over adjacent pairs (left, right) (using zip(words, words[1:]), so pairs never cross sentence boundaries). For each pair, increment counts[left][right], then compare right with best[left]. Replace the stored best if right has a higher count, or an equal count and a smaller word. A query is just best.get(word), which gives None for unknown words and for words that never had a follower.
Why it is correct
Invariant: after each pair is processed, best[left] is the true maximum for left under the ordering (higher count first, then smaller word).
- When
leftgets its first follower, that follower is the only candidate. - Processing a pair raises exactly one count,
counts[left][right], by 1. All other followers ofleftkeep their counts, andbest[left]already beat them, so it still does. The only word that can newly overtake the stored best isright, so comparing those two is enough. Ifrightis already the best, its lead only grows and nothing changes.
This relies on counts never decreasing, which holds because there are no removals.
Edge cases follow naturally: the last word of a sentence creates no pair, unknown words have no entry in best, ties are resolved explicitly by comparing words (independent of insertion order), and empty or one-word sentences give no pairs from zip. Because split() with no arguments collapses whitespace, extra spaces are harmless.
Complexity
add_sentences: O(L) hash operations for L words in the batch (times word length for hashing and comparing strings).get_next_word: O(1).- Space: O(P), where P is the number of distinct adjacent pairs, at most the total number of words.
Reference solution
from collections import defaultdict
from typing import List, Optional
def simulate_follower_engine(operations: List[str], arguments: List[List]) -> List[Optional[str]]:
counts = defaultdict(dict) # left -> {right: count}
best = {} # left -> best follower so far
results = []
for operation, args in zip(operations, arguments):
if operation == "add_sentences":
for sentence in args[0]:
words = sentence.split()
for left, right in zip(words, words[1:]):
successors = counts[left]
successors[right] = successors.get(right, 0) + 1
current = best.get(left)
if current is None:
best[left] = right
else:
current_count = successors[current]
candidate_count = successors[right]
if candidate_count > current_count or (
candidate_count == current_count and right < current
):
best[left] = right
results.append(None)
elif operation == "get_next_word":
results.append(best.get(args[0]))
else:
raise ValueError("unknown operation")
return results