At end, set is_end_of_word = True and self.score = score.
_collect_all_words(node, prefix) (Helper):
Recursive DFS.
If node.is_end_of_word, add (prefix, node.score) to results list.
For each child, recurse with updated prefix.
autocomplete(self, prefix):
Traverse trie using prefix.
If prefix not found, return empty list.
Call helper on the current node to get all suffixes.
Format output (concat prefix + suffix).
Sort the final list by score.
Refining the Scoring Logic:
Usually, autocomplete systems update scores. If I insert "apple" with score 10, and then insert "apple" with score 5, should it be 5 or 15?
To keep it simple, I'll assume the score is the current weight (e.g., search frequency). Inserting a duplicate overwrites the score.
Self-correction: Actually, accumulating scores is often more realistic (counting frequency), but overwriting is easier to demonstrate specific weights. Let's stick to setting the score.
Optimization (Optional but good to mention):
A standard trie traversal is O(L) for the prefix + O(N) for finding all candidates. Sorting is O(KlogK).
A real-world optimization is storing the "top N" results directly at every node, so you don't have to traverse deep down. This makes the search relative to the output size (essentially).
Code Structure:
python
class TrieNode:
...
class AutocompleteSystem:
...
# insert method
# search/autocomplete method
Example Usage:
Insert "hello" (5), "hell" (2), "heat" (10).
Search "he".
Expected: "heat" (10), "hello" (5), "hell" (2).
Drafting the Code (Mental or Scratchpad):
python
class TrieNode:
def __init__(self):
self.children = {}
self.score = 0
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word, score):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
node.score = score # Overwriting for simplicity
def search(self, prefix):
node = self.root
for char in prefix:
if char not in node.children:
return []
node = node.children[char]
# Now node is the root of the subtree for this prefix
results = []
self._dfs(node, prefix, results)
return results
def _dfs(self, node, prefix, results):
if node.is_end:
results.append((prefix, node.score))
for char, child_node in node.children.items():
self._dfs(child_node, prefix + char, results)
Adding Sorting:
The search method should return a sorted list.
sorted(results, key=lambda x: x[1], reverse=True)
Final Polish:
I'll wrap this in a clean Python script with comments explaining the time complexity and usage. I will also make sure to handle the case where the prefix is empty (return everything?).
Let's refine the return format. A list of strings or a list of tuples? The prompt asks for "autocomplete", so usually a list of strings is desired, but since it mentions scoring, showing the score in the output is helpful for verification.
Constraint Check:
"implements autocomplete with trie and scoring".
Trie used? Yes.
Scoring used? Yes.
Autocomplete logic? Yes.
I will write the solution in Python as it is the most accessible language for data structure demos.
Code Plan:
Define TrieNode.
Define Trie class with insert and autocomplete.
Add a dfs helper method to gather words.
Create a main block to demonstrate usage:
Add words with different frequencies.
Search for prefixes.
Show the ranking.
Let's consider the "Top N" optimization. While efficient, it complicates the code significantly (handling stale data, inserting into sorted lists at every node). For a "write a program" prompt, the standard Trie + DFS approach is the expected answer for correctness and understanding, unless "production grade" is specified. I will stick to the standard approach.
Wait, what if I want to update a score? E.g., user searches "foo" again. The insert logic node.score = score handles replacement. If I wanted accumulation, it would be node.score += score. I'll stick to assignment for simplicity, acting as if we are loading a static dictionary of popular terms.
One detail: The _dfs method.
If the prefix itself is a word (e.g. prefix="app", word="app"), it should be included. node.is_end check handles that.
Final code structure looks solid. I will proceed with generating the Python code.
Here is a complete implementation in Python.
This solution uses a Trie (Prefix Tree) to store the words. Each node contains a dictionary of children nodes and a dictionary of scores. The scores are stored at the specific node that marks the end of a word.
The Algorithm
Insertion: When adding a word, we traverse down the tree character by character. At the final node, we store the score.
Lookup: When a user types a prefix, we navigate to the node representing that prefix.
Collection (DFS): From that node, we perform a Depth-First Search (DFS) to find all child nodes that represent complete words.
Ranking: We aggregate these words and their scores, then sort them to return the top suggestions.
Python Implementation
python
Breakdown of How it Works
TrieNode Class:
children: A hash map storing the next characters.
is_end_of_word: A boolean flag.
score: An integer. If is_end_of_word is True, this stores the "weight" or popularity of that specific word.
search Method:
First, it checks if the prefix exists. If you type "xyz" and no words start with "xyz", it returns an empty list immediately.
If the prefix exists (e.g., "hel"), it stops at the node for 'l'.
It calls _dfs_collect to find every possible word completion downwards (e.g., "hello", "help", "helicopter").
Scoring and Sorting:
We collect a list of tuples: (word, score).
We sort this list based on the score. In Python, sort(key=lambda x: -x[1]) sorts numbers in descending order (highest score first).
Finally, we slice the list ([:top_k]) to return only the requested number of suggestions.
O(1)
Decision: I will implement the standard traversal first as it demonstrates the algorithm clearly. I can mention the optimization in the explanation.
class TrieNode:
def __init__(self):
# Maps character -> TrieNode
self.children = {}
# Marks if this node is the end of a word
self.is_end_of_word = False
# Stores the score/weight of the word ending here
self.score = 0
class AutocompleteSystem:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str, score: int):
"""
Inserts a word into the trie with a specific score (frequency/weight).
"""
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
# Mark the end of the word and update the score
node.is_end_of_word = True
node.score = score
def _dfs_collect(self, node: TrieNode, prefix: str):
"""
Helper method to traverse the trie (DFS) and collect all words
starting from a given node.
"""
results = []
# If this node is a complete word, add it to results
if node.is_end_of_word:
results.append((prefix, node.score))
# Recursively visit children
for char, child_node in node.children.items():
results.extend(self._dfs_collect(child_node, prefix + char))
return results
def search(self, prefix: str, top_k: int = 5):
"""
Returns the top K suggestions for a given prefix based on score.
"""
node = self.root
# 1. Navigate to the node corresponding to the prefix
for char in prefix:
if char not in node.children:
return [] # Prefix not found
node = node.children[char]
# 2. Collect all valid words from this node downwards
# (word, score) tuples
candidates = self._dfs_collect(node, prefix)
# 3. Sort candidates by score in descending order
# If scores are equal, sort alphabetically (optional tie-breaker)
candidates.sort(key=lambda x: (-x[1], x[0]))
# 4. Return top K results (just the words)
return [word for word, score in candidates[:top_k]]
# ==========================================
# Example Usage
# ==========================================
if __name__ == "__main__":
# Initialize system
ac_system = AutocompleteSystem()
# Dataset: Word and Frequency (Score)
# Higher score = more popular
database = [
("hello", 100),
("hell", 5),
("heat", 40),
("helium", 15),
("help", 80),
("helicopter", 25),
("happy", 90),
("apple", 95),
("application", 50),
("app", 120),
("ape", 10)
]
print("Building Trie...")
for word, score in database:
ac_system.insert(word, score)
# Test 1: Prefix "hel"
query = "hel"
print(f"\nSearching for: '{query}'")
suggestions = ac_system.search(query, top_k=5)
print(f"Suggestions: {suggestions}")
# Expected logic: hello(100), help(80), heat(40)...
# Test 2: Prefix "ap"
query = "ap"
print(f"\nSearching for: '{query}'")
suggestions = ac_system.search(query, top_k=5)
print(f"Suggestions: {suggestions}")
# Expected logic: app(120), apple(95), application(50)...
# Test 3: Prefix "hea" (limited to top 1)
query = "hea"
print(f"\nSearching for: '{query}' (Top 1)")
suggestions = ac_system.search(query, top_k=1)
print(f"Suggestions: {suggestions}")