Most Frequent Follower Lookup with Command Replay
Data Structure DesignAuto-graded · 21 test casesLast updated
Simulate a train/predict command stream for a word-follower model, precomputing the top follower per word so each prediction is a single hash lookup, with a precise tie-break rule.
Word Follower Model
You are given a stream of commands for a tiny text model that learns which word most often comes right after another word. Process the commands in order and report the result of each one.
Commands
You receive two lists of equal length. commands[i] is the name of the i-th command, and payloads[i] is a list holding exactly one string, which is that command's argument.
"train": the argument is a piece of text. Split it on whitespace into words, preserving case. For every pair of neighbouring words(a, b)in that text, record thatbfollowedaonce. Counts accumulate across alltraincommands. Pairs are formed only inside a single text, never across the end of one text and the start of the next. Text with fewer than two words adds nothing."predict": the argument is a single word. Return the word that has followed it most often so far. If the word has never been seen with a follower, returnNone.
Output
Return a list with one entry per command, in order:
Nonefor everytraincommand.- The predicted word (a string) or
Nonefor everypredictcommand.
Matching rules
- Matching is exact and case-sensitive.
"The"and"the"are different words. No punctuation stripping is done. - A word that appears only as the last word of a text, and nowhere else with a follower, has no followers, so predicting it gives
None. - The query word is looked up as given. An empty string or any word never seen with a follower gives
None.
Tie-break rule
If several followers share the highest count for a word, return the one that first appeared as a follower of that word across the entire history of train commands (earliest first occurrence, counting from the very first command). Later counts do not change this preference among tied words.
For example, if x first followed w before y did, and both currently have the same top count, the answer for w is x, even if y reached that count earlier than x did.
Aim to make each predict a constant-time lookup after training, not a scan over all followers.
Constraints
1 <= len(commands) == len(payloads).- Each command is either
"train"or"predict". - Each
payloads[i]contains exactly one string. - Texts may be empty or contain only whitespace.
- The total number of words across all texts fits comfortably in memory.
- The number of distinct words is manageable.
Examples
Example 1
Input: replay_follower_commands(['train', 'predict', 'predict', 'predict'], [['the cat chased the mouse and the cat ate the cheese'], ['the'], ['cat'], ['unknown']])
Output: [None, 'cat', 'chased', None]
Example 2
Input: replay_follower_commands(['train', 'predict', 'predict', 'train', 'predict'], [['one two two three'], ['two'], ['one'], ['two three two'], ['two']])
Output: [None, 'two', 'two', None, 'three']
Example 3
Input: replay_follower_commands(['train', 'predict', 'predict'], [[''], ['anything'], ['']])
Output: [None, None, None]
Hints
Hint 1
Keep, for each word, a dictionary from follower to its count. Dictionaries remember insertion order, which helps with the tie-break rule.
Hint 2
To make predict O(1), store the current best follower for each word and update it while training, instead of searching at query time.
Hint 3
Counts only ever go up. When a follower's count rises to c, it becomes the best if c exceeds the best count, or if it ties and was first seen earlier than the current best. Store each follower's first-seen rank to compare.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
All the work goes into train, so that predict is a single dictionary lookup.
For each word a we keep:
counts[a][b]: how many timesbhas directly followeda.rank[a][b]: the order in whichbfirst appeared as a follower ofa(0 for the first, 1 for the second, and so on).best[a]: the current answer fora.
When training on a text, split it on whitespace and walk over each neighbouring pair (a, b). Pairs are made only inside one text, so nothing is joined across train calls. For each pair:
- If
bhas not followedabefore, give it the next rank and a count of 0. - Increment
counts[a][b]. - Update
best[a]. The new candidatebwins if its count is strictly greater than the current best's count, or if the counts are equal andbhas a smaller rank (it appeared earlier).
predict(word) returns best.get(word), which is None when the word has no recorded followers.
Why it is correct
Counts never decrease, and each step changes exactly one count. Suppose best[a] is correct under the rule "highest count, ties broken by smallest rank" before the step, and follower b is incremented.
- Every follower other than
bis unchanged, so the old best still beats all of them. - The only follower whose standing changed is
b, so the new best is whichever of the old best andbwins the comparison.
By induction the stored best is always correct. The rank comparison implements the tie-break exactly: among tied followers, the one that first appeared earliest wins, regardless of who reached the tied count first.
A first follower of a word has no competitor, so it is set directly as the best.
Edge cases fall out naturally. An empty text or a single-word text gives no pairs. A word that is only ever last in a text never gets an entry. An unseen or empty query returns None.
Complexity
Let N be the total number of words across all training texts.
train: O(length of text) on average, with each pair handled in O(1).predict: O(1) on average.- Space: O(P), where P is the number of distinct adjacent word pairs.
Reference solution
from typing import List, Optional, Dict
def replay_follower_commands(commands: List[str], payloads: List[List[str]]) -> List[Optional[str]]:
# word -> {follower: count}; dict order = order of first appearance as follower
counts: Dict[str, Dict[str, int]] = {}
# word -> {follower: first-seen rank among followers of that word}
rank: Dict[str, Dict[str, int]] = {}
# word -> current best follower
best: Dict[str, str] = {}
results: List[Optional[str]] = []
for cmd, args in zip(commands, payloads):
if cmd == "train":
words = args[0].split()
for i in range(len(words) - 1):
a, b = words[i], words[i + 1]
fc = counts.setdefault(a, {})
fr = rank.setdefault(a, {})
if b not in fc:
fc[b] = 0
fr[b] = len(fr)
fc[b] += 1
cur = best.get(a)
if cur is None:
best[a] = b
else:
if fc[b] > fc[cur] or (fc[b] == fc[cur] and fr[b] < fr[cur]):
best[a] = b
results.append(None)
elif cmd == "predict":
results.append(best.get(args[0]))
return results