Leetcode #642: Design Search Autocomplete System
In this guide, we solve Leetcode #642 Design Search Autocomplete System in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character '#').
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Depth-First Search, Design, Trie, String, Data Stream, Sorting, Heap (Priority Queue)
Intuition
We need to repeatedly access the smallest or largest element as the input changes.
A heap provides fast insertions and removals while keeping order.
Approach
Push candidates into the heap as you scan, and pop when you need the best element.
Keep the heap size bounded if the problem requires a top-k structure.
Steps:
- Push candidates into a heap.
- Pop the best candidate when needed.
- Maintain heap size or invariants.
Example
Input
["AutocompleteSystem", "input", "input", "input", "input"]
[[["i love you", "island", "iroman", "i love leetcode"], [5, 3, 2, 2]], ["i"], [" "], ["a"], ["#"]]
Output
[null, ["i love you", "island", "i love leetcode"], ["i love you", "i love leetcode"], [], []]
Explanation
AutocompleteSystem obj = new AutocompleteSystem(["i love you", "island", "iroman", "i love leetcode"], [5, 3, 2, 2]);
obj.input("i"); // return ["i love you", "island", "i love leetcode"]. There are four sentences that have prefix "i". Among them, "ironman" and "i love leetcode" have same hot degree. Since ' ' has ASCII code 32 and 'r' has ASCII code 114, "i love leetcode" should be in front of "ironman". Also we only need to output top 3 hot sentences, so "ironman" will be ignored.
obj.input(" "); // return ["i love you", "i love leetcode"]. There are only two sentences that have prefix "i ".
obj.input("a"); // return []. There are no sentences that have prefix "i a".
obj.input("#"); // return []. The user finished the input, the sentence "i a" should be saved as a historical sentence in system. And the following input will be counted as a new search.
Python Solution
class Trie:
def __init__(self):
self.children = [None] * 27
self.v = 0
self.w = ''
def insert(self, w, t):
node = self
for c in w:
idx = 26 if c == ' ' else ord(c) - ord('a')
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.v += t
node.w = w
def search(self, pref):
node = self
for c in pref:
idx = 26 if c == ' ' else ord(c) - ord('a')
if node.children[idx] is None:
return None
node = node.children[idx]
return node
class AutocompleteSystem:
def __init__(self, sentences: List[str], times: List[int]):
self.trie = Trie()
for a, b in zip(sentences, times):
self.trie.insert(a, b)
self.t = []
def input(self, c: str) -> List[str]:
def dfs(node):
if node is None:
return
if node.v:
res.append((node.v, node.w))
for nxt in node.children:
dfs(nxt)
if c == '#':
s = ''.join(self.t)
self.trie.insert(s, 1)
self.t = []
return []
res = []
self.t.append(c)
node = self.trie.search(''.join(self.t))
if node is None:
return res
dfs(node)
res.sort(key=lambda x: (-x[0], x[1]))
return [v[1] for v in res[:3]]
# Your AutocompleteSystem object will be instantiated and called as such:
# obj = AutocompleteSystem(sentences, times)
# param_1 = obj.input(c)
Complexity
The time complexity is O(n log n). The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.