Phrase Completion Engine with Windowed Context Counts
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulate a command sequence on a context-based next-word model, using hash maps of counts and a lexicographic tie-break.
Phrase Completion Engine with Windowed Context Counts
You are building a tiny text-completion engine. It learns from sentences and, given a short sequence of words (the context), suggests the word that most often comes right after that context.
The engine has a fixed window size window. Every context has exactly window words.
Operations
You are given the window size and two parallel lists: commands and payloads. The i-th command is applied to the engine in order, using payloads[i] as its argument list.
"train":payloads[i][0]is a list of sentence strings. Each sentence is split into words on whitespace, and empty tokens are ignored, so repeated spaces do not matter. For each sentence on its own, look at every run ofwindowconsecutive words. The word immediately after that run is its follower. Add one to the count of that (context, follower) pair. Sentences are processed independently, so a context never spans two sentences. A sentence withwindowwords or fewer adds nothing. Counts accumulate across multiple"train"commands."predict":payloads[i][0]is a list of words, the query context. Return the follower with the highest count for that context.- If several followers share the highest count, return the lexicographically smallest one (standard string comparison, case-sensitive, no normalization).
- If the query's length is not equal to
window, or the context was never seen in training, returnNone.
Words are compared exactly as given, so "The" and "the" are different words.
Output
Return a list with one entry per command, in order. A "train" command yields None. A "predict" command yields the suggested word, or None as described above.
Constraints
windowis a non-negative integer. Withwindow = 0the context is empty, and the prediction is the most frequent word overall (an empty query list is then a valid context).len(commands) == len(payloads).- Every command is either
"train"or"predict". - Sentences contain only words separated by whitespace. Total word count across all training is moderate, so a single pass over each sentence is expected.
- Words are non-empty strings after splitting.
- Prediction should be a direct lookup on the context, not a scan over all stored contexts.
Examples
Example 1
Input: simulate_phrase_completer(2, ['train', 'predict', 'predict', 'predict'], [[['the cat sat on the mat', 'the cat ate the fish']], [['the', 'cat']], [['cat', 'sat']], [['the']]])
Output: [None, 'ate', 'on', None]
Example 2
Input: simulate_phrase_completer(1, ['train', 'predict', 'predict', 'predict'], [[['a b c', 'a b d', 'a b c']], [['a']], [['b']], [['x']]])
Output: [None, 'b', 'c', None]
Hints
Hint 1
Treat each run of `window` consecutive words in a sentence as a key (a tuple works well) and keep a count per follower word under that key.
Hint 2
Split with the default whitespace split so extra spaces vanish, and only slide the window over positions where a following word exists. Never join words from different sentences.
Hint 3
To pick the answer, choose the follower with the largest count and break ties with the smaller string, for example by minimizing the pair (-count, word). Return None if the query length differs from window or the key is missing.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a small simulation over a hash-map-based n-gram model.
- Keep a dictionary that maps each context (a tuple of
windowwords) to another dictionary of follower counts. - On
"train", split each sentence on whitespace and slide a window of sizewindowover it. Stop early enough that a follower word always exists, so the loop runs forlen(words) - windowpositions. For each position, increment the count of the follower under its context. Each sentence is handled alone, so contexts never cross sentence boundaries. Counts persist, so repeated training simply adds to them. - On
"predict", returnNoneif the query length is notwindowor the context key is missing. Otherwise pick the follower minimizing(-count, word): the highest count wins, and ties go to the lexicographically smaller word. - Append
Nonefor every train command and the prediction for every predict command.
Why it is correct
Every occurrence of a context followed by a word is counted exactly once, because each valid window position in each sentence is visited once. The final selection compares followers on exactly the specified rule, highest count then smallest string, so it returns the required answer. Length mismatches and unseen contexts both lead to None. With window = 0 the context is the empty tuple, which naturally gives the globally most frequent word.
Complexity
- Training:
O(W * window)time forWtotal words, since each window builds a tuple of lengthwindow. - Prediction:
O(window + F)time, whereFis the number of distinct followers of that context. Hashing the tuple costsO(window)and the scan over followers costsO(F). To make this strictlyO(window), store the current best follower per context and update it whenever a count increases. This is valid because counts only ever grow. - Space:
O(W * window)in the worst case for the stored contexts and followers.
Reference solution
from typing import Dict, List, Optional, Tuple
def simulate_phrase_completer(window: int, commands: List[str], payloads: List[List]) -> List[Optional[str]]:
# context tuple -> {follower -> count}
counts: Dict[Tuple[str, ...], Dict[str, int]] = {}
results: List[Optional[str]] = []
for cmd, args in zip(commands, payloads):
if cmd == "train":
for sentence in args[0]:
words = sentence.split()
for i in range(len(words) - window):
ctx = tuple(words[i:i + window])
nxt = words[i + window]
followers = counts.setdefault(ctx, {})
followers[nxt] = followers.get(nxt, 0) + 1
results.append(None)
elif cmd == "predict":
query = args[0]
if len(query) != window:
results.append(None)
continue
followers = counts.get(tuple(query))
if not followers:
results.append(None)
continue
best = min(followers.items(), key=lambda kv: (-kv[1], kv[0]))
results.append(best[0])
else:
results.append(None)
return results