Most Likely Follower Lookup via Operation Log
Data Structure DesignAuto-graded · 13 test casesLast updated
Simulate a bigram next-word model from an operation log, returning the most frequent follower with lexicographic tie-breaking and an empty string when none exists.
Follower Prediction Simulator
You are given a log of operations to run against a small "next word" model. The model learns from several token sequences and answers which token most often comes right after a given token.
Learning rule
Two tokens form a transition (a, b) when b comes immediately after a inside the same sequence. Transitions never cross sequence boundaries: the last token of one sequence is not linked to the first token of the next. Each occurrence of a transition adds 1 to its count, whether it repeats within one sequence or across several.
Operations
operations and arguments have the same length. arguments[i] is the argument list for operations[i]. Process them in order.
"WordPredictor": builds the model. Usearguments[i][0]as the training collection. Each element of that collection is one sequence, read element by element. If a sequence is a plain string, its individual characters are its elements. AppendNoneto the output. Constructing the model again replaces the old one."predict":arguments[i][0]is the query token. Append the token that most frequently follows it across all training data. If several followers tie for the highest count, append the lexicographically smallest of them. If the query token has no follower (it was never seen, or it only ever appears at the end of sequences), append"". If no model has been built yet, append"".
Any other operation name should raise ValueError.
Return the list of outputs, one per operation, in order.
Notes
- Empty sequences and one-element sequences produce no transitions.
- A token can follow itself (for example,
["go", "go"]gives the transitiongo -> go). - Queries are compared exactly against the tokens as they were read from the training data.
Constraints
1 <= len(operations) == len(arguments) <= 10^5 + 1- Training collection has at most
10^4sequences, each with at most10^3elements, and at most2 * 10^5elements in total. - Tokens consist of lowercase English letters.
- Up to
10^5predictoperations, each expected to be answered in average constant time after construction.
Examples
Example 1
Input: simulate_next_word_model(['WordPredictor', 'predict', 'predict', 'predict', 'predict'], [[['the', 'quick', 'brown', 'fox'], ['the', 'lazy', 'dog'], ['the', 'quick', 'rabbit']], ['the'], ['quick'], ['dog'], ['cat']])
Output: [None, '', '', '', '']
Hints
Hint 1
Only adjacent elements inside one sequence matter, so loop over each sequence separately and never over a flattened list.
Hint 2
Keep a map from each token to a map of follower counts. Once all counts are known, the best follower of each token can be computed a single time.
Hint 3
Pick the best follower with the key (-count, word), then answer each query with one dictionary lookup that defaults to an empty string.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Handle the log in order. When the constructor operation appears, count transitions and precompute the answer for every token. Each query then becomes one dictionary lookup.
- Counting. For each sequence, walk over adjacent positions
(i, i + 1)and incrementcounts[seq[i]][seq[i + 1]]. Because the loop runs per sequence, no transition crosses a sequence boundary. Sequences with fewer than two elements add nothing. - Precomputing the winner. For every token that has at least one follower, choose the follower minimizing
(-count, word). This picks the highest count, and among equal counts the lexicographically smallest word. Store it inbest[token]. - Answering queries.
predictreturnsbest.get(token, ""). A token that was never seen, or that only appears at the end of sequences, has no entry, so it correctly gives"". If no model has been built yet, the answer is"". - Any unknown operation name raises
ValueError. Rebuilding the model replaces the old one.
Training elements are read exactly as given. If a sequence is a plain string, its characters are the elements, so multi-letter queries then match nothing and return "".
Why it is correct
Every adjacent in-sequence pair is counted exactly once, so each count equals the true number of occurrences. The key (-count, word) is a total order on a token's followers, so its minimum is the unique correct answer under the tie-break rule. Tokens without followers never get an entry, which gives the required empty-string result.
Complexity
With N total training elements, Q queries and L the maximum token length:
- Construction takes
O(N * L)expected time, covering counting plus one pass over the distinct transitions to pick winners. - Each
predicttakesO(L)expected time, which is average constant time apart from hashing the string. - Space is
O(T), whereTis the number of distinct transitions.
Reference solution
from collections import Counter, defaultdict
from typing import List
def simulate_next_word_model(operations: List[str], arguments: List[List]) -> List:
best = None
results = []
for operation, args in zip(operations, arguments):
if operation == "WordPredictor":
sequences = args[0]
counts = defaultdict(Counter)
for sequence in sequences:
for i in range(len(sequence) - 1):
counts[sequence[i]][sequence[i + 1]] += 1
best = {}
for word, successors in counts.items():
best[word] = min(successors, key=lambda w: (-successors[w], w))
results.append(None)
elif operation == "predict":
results.append(best.get(args[0], "") if best is not None else "")
else:
raise ValueError("Unknown operation")
return results