Replay a Typing Session Against a Ranked Suggestion History
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulate keystroke-by-keystroke search suggestions over a frequency-weighted history that grows as queries are committed, ranking the top 3 matches by count and then text.
Replay a Typing Session Against a Ranked Suggestion History
A search box keeps a history of past queries, each with a count of how many times it was searched. As a user types one character at a time, the box suggests the best matching past queries. When the user finishes a query, that query is added to the history.
You are given the initial history and a recorded list of keystrokes. Replay the keystrokes in order and return the suggestions produced after each one.
Inputs
sentences: a list of strings, the initial history queries.times: a list of integers, wheretimes[i]is the count forsentences[i]. If the same string appears more than once insentences, its counts are added together.operations: a list of strings with the same length asarguments. Every entry must be"input". If any entry is something else, raiseValueError.arguments: a list wherearguments[i]is a one-element list[c]holding the character typed for thei-th operation.
Behavior of each keystroke
The replay keeps a buffer of the characters typed since the last '#'. It starts empty.
cis not'#': appendcto the buffer. Collect every history query that starts with the whole buffer. Order them by count, highest first. Break ties by plain string comparison (ASCII order, smaller first). Output the first 3, or all of them if fewer than 3 match.cis'#': the query is finished.- If the buffer is non-empty, add its text to the history. If the text is already in the history, increase its count by 1. Otherwise add it with count 1.
- Clear the buffer.
- Output an empty list
[].
Each operation produces exactly one list in the result, in the same order as the operations.
Return value
A list of lists of strings, one inner list per operation.
Notes
- A space
' 'is an ordinary character. In ASCII it sorts before every lowercase letter. - A
'#'with an empty buffer changes nothing and outputs[]. - A finished query that matched nothing while being typed is still added to the history with count 1.
- A query finished with
'#'counts as history only from the next keystroke onward, so it affects the following session's suggestions. - Once a prefix matches nothing, every further keystroke in that session outputs
[]until the next'#'.
Constraints
1 <= len(sentences) == len(times) <= 20001 <= times[i] <= 1001 <= len(sentences[i]) <= 100- Each typed character is a lowercase letter
'a'-'z', a space' ', or'#'. len(operations) == len(arguments) <= 20000
Examples
Example 1
Input: replay_suggestions(['pin', 'pinterest', 'pinecone', 'pine'], [5, 3, 2, 2], ['input', 'input', 'input', 'input', 'input', 'input', 'input'], [['p'], ['i'], ['n'], ['e'], ['#'], ['p'], ['#']])
Output: [['pin', 'pinterest', 'pine'], ['pin', 'pinterest', 'pine'], ['pin', 'pinterest', 'pine'], ['pine', 'pinecone'], [], ['pin', 'pine', 'pinterest'], []]
Hints
Hint 1
Keep two things: a dictionary from query text to its count, and the buffer of characters typed so far in the current session.
Hint 2
Ranking is just a sort key of (-count, text). Take the first 3 after sorting the matches.
Hint 3
Counts only change when '#' is typed, so within one session the matches for a longer buffer are a subset of the matches for the shorter one. You can narrow a candidate list instead of rescanning the whole history.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep a dictionary counts that maps each history query to its frequency. Initial duplicates are summed while building it. Also keep the current buffer string.
For each operation:
- Not
'#': append the character to the buffer. Select the history queries that start with the buffer, sort them by(-count, text), and output the first 3. '#': if the buffer is non-empty, increase its count by 1, creating the entry with count 1 if it is new. Clear the buffer and output[].- Any other operation name: raise
ValueError.
To avoid rescanning the whole history on every keystroke, keep a candidate list for the current session. The first keystroke filters the whole history. Each later keystroke filters only the previous candidates, because a longer prefix can only match a subset of what the shorter prefix matched. The list is reset on '#'.
Why it is correct
- The candidate list always equals the set of history queries that start with the current buffer. Counts and membership change only on
'#', and the candidate list is reset at that point, so no stale data is used. - The sort key
(-count, text)gives count descending and then ASCII ascending. Texts are unique dictionary keys, so the order is fully determined and the first 3 are exactly the required suggestions. - A finished query is added to the history only at
'#', so it first appears in suggestions in the next session, with its updated count. - Once the candidate list is empty, it stays empty for the rest of the session, giving
[]as required. - An empty-buffer
'#'records nothing and outputs[].
Complexity
Let n be the number of history queries, L the maximum query length, and m the number of current matches.
- Keystroke: the first of a session costs
O(n * L)for filtering. Later ones costO(m * L)for filtering. Each also paysO(m log m)for the sort. '#':O(L).- Space:
O(n * L)for the history.
A trie with a cursor and per-node query sets is a possible optimization for much larger histories, but this approach fits these limits.
Reference solution
from typing import List
def replay_suggestions(sentences: List[str], times: List[int],
operations: List[str],
arguments: List[List[str]]) -> List[List[str]]:
counts = {}
for s, f in zip(sentences, times):
counts[s] = counts.get(s, 0) + f
buffer = ""
candidates = None # None means "whole history" (start of a session)
results = []
for operation, args in zip(operations, arguments):
if operation != "input":
raise ValueError("Unknown operation")
c = args[0]
if c == "#":
if buffer:
counts[buffer] = counts.get(buffer, 0) + 1
buffer = ""
candidates = None
results.append([])
else:
buffer += c
pool = counts if candidates is None else candidates
candidates = [s for s in pool if s.startswith(buffer)]
ranked = sorted(candidates, key=lambda s: (-counts[s], s))
results.append(ranked[:3])
return results