Problem 63 · Strings & Tries
Search Autocomplete System (Top-3 by Frequency)
01Problem
Design an autocomplete system initialized with historical sentences and counts. input(c) appends c to the current query and returns the top 3 historical sentences with that prefix, ranked by count desc then lexicographically; '#' ends the query, records it, and returns [].
02Key insight
Keep a trie whose nodes cache the top-k sentences for their prefix; on each record, update the cache along the sentence path. Track the current node across keystrokes so each character is O(1) navigation plus a k-sized read.
03Solution
Try it first.
TimeO(L * k log k) record, O(1) per keystroke
SpaceO(total chars * k)
tests.py · 6 passing
tests.pypython8 lines
ac = AutocompleteSystem(["i love you", "island", "ironman", "i love leetcode"], [5, 3, 2, 2])
assert ac.input("i") == ["i love you", "island", "i love leetcode"]
assert ac.input(" ") == ["i love you", "i love leetcode"]
assert ac.input("a") == []
assert ac.input("#") == []
assert ac.input("i") == ["i love you", "island", "i love leetcode"]
for ch in " a#": ac.input(ch) # "i a" now has count 2, ties broken lexicographically
assert ac.input("i") == ["i love you", "island", "i a"]04Staff-level follow-up
At web scale? Precompute top-k per prefix offline (MapReduce over query logs), shard by prefix, serve from cache/CDN, and blend in a small real-time trending layer with decayed counts.