p104 — Design Autocomplete System — Hints
-
It’s a state machine, not a one-shot query.
input(c)builds up a buffer over many calls. You needself.buf: strandself.cur: Optional[Node]as instance state. Reset both on'#'. -
Trie node holds frequency at the terminal (or as
countat every internal sentence-end). Insert a sentence by descending one char at a time, then+= freqon the terminal node’s count field. -
Tie-break is
(-frequency, sentence), not(-frequency, -sentence). Frequencies sort descending, sentences sort ASCENDING on ties. Easiest: collect all candidates from the subtree, sort withkey=lambda x: (-x[1], x[0]), take first 3. -
Off-trie behavior. If
self.curisNone(we’ve already gone off-trie this query), or if the next char has no child, setself.cur = Noneand return[]. Stay off-trie until'#'arrives — don’t try to re-find a matching prefix mid-stream. -
'#'commits the current buffer. Increment count if the sentence already exists; insert with count 1 if new. Then reset state. The buffer can contain spaces (treat them as ordinary characters).
If stuck: see solution.py.