1. Understand the Goal: The user wants a program that implements "autocomplete with a trie and scoring." This implies:
* Data Structure: A Trie (Prefix Tree) to store words efficiently.
* Functionality: Given a prefix, return a list of matching words.
* Feature: Scoring/Ranking. The results shouldn't be random; they should be ordered by some metric (e.g., frequency, weight, timestamp). Let's stick to frequency/weight as it's the most common use case for autocomplete.
-
Determine the Scope & Language:
- Language: Python is the standard choice for algorithmic demonstrations due to readability and built-in data structures. I'll use Python 3.
- Components:
TrieNode class: Stores children (dictionary), end-of-word flag, and the score/weight.
Trie class: Manages insertion and search.
Autocomplete System: Handles input, traverses the trie, collects candidates, sorts them, and returns the top results.
-
Designing the Trie Structure:
- Node: Needs a map of
char -> TrieNode. Needs to store the score. Does the score live at the end node or every node?
- Option A: Store score only at the end node.
- Option B: Store score at every node (intermediate). This helps with "hot" prefixes, but for standard autocomplete, usually we just want the score of the word formed.
- Refinement: Let's store the score at the node that marks the end of a word. Also, it might be useful to store the word itself at the end node to avoid passing strings around during recursion, or just reconstruct it. Let's store
(word, score) at the end node for simplicity in retrieval.
-
Designing the Search Algorithm:
- Input: A prefix string.
- Step 1: Traverse the Trie based on the prefix.
- If traversal fails (hits a null), return empty list.
- Step 2: Once at the "prefix node", perform a traversal (DFS/BFS) to find all complete words below this node.
- Step 3: Collect all candidates
[(word, score), ...].
- Step 4: Sort the candidates by score (descending) and alphabetically (ascending) as a tie-breaker.
- Step 5: Return the top k results.
-
Optimization Consideration (The "Lazy" vs. "Proactive" approach):
- Naive approach: Find the node, then DFS all children to find words, then sort. This is O(L+N⋅M) where N is number of nodes under prefix and M is average word length. The sort is where is number of words found.
-
Drafting the Code (Mental or Scratchpad):
-
Refining the DFS:
- It needs to construct the full words.
- Input:
node, current_prefix.
- Logic:
- If
node.is_end: add (current_prefix, node.score) to results.
- For
char, child_node in node.children: recurse dfs(child_node, current_prefix + char).
-
Putting it together in a Script:
- Define classes.
- Create a helper class
AutocompleteSystem.
- Add a
main block to demonstrate functionality.
- Test cases: Insert "apple" (5), "app" (3), "apricot" (2). Search "ap". Should return ["apple", "app", "apricot"].
-
Edge Cases:
- Prefix not found.
- Case sensitivity (convert to lower).
- Punctuation (simple strip or keep? Let's keep it simple, ignore normalization unless asked, but usually good to mention).
- Limiting results (Top 3, Top 5).
-
Code Structure Plan:
TrieNode: The building block.
Trie: Handles insert and collecting _get_all_words.
Autocomplete: The wrapper that sorts and limits.
-
Writing the actual Python code (Mental check of syntax):
sorted(candidates, key=lambda x: (-x[1], x[0])) -> Sort by score desc, then word asc.
-
Review against "Scoring" requirement:
- The prompt specifically asks for "scoring". This usually implies that when a user types, we want the most relevant words.
- Implementation: The node needs to hold a numerical weight.
-
Final Polish:
- Add comments explaining the logic.
- Ensure the example usage covers the sorting requirement clearly.
(Self-Correction during drafting):
Should I implement the "caching" optimization (storing top 3 at every node)?
- Pros: Faster search.
- Cons: Much more complex code, harder to explain in a single snippet.
- Decision: Stick to DFS + Sort. It is the standard interview answer for this problem unless "Optimize for speed" is explicitly requested.
Let's write the solution.
- Class Node: children map, end flag, score.
- Insert: Loop chars, make nodes, set end score.
- Search: Loop prefix. If found, DFS. Sort results.
Let's add a usage example with sentences, like a search history.
"i love you", score 5
"ironman", score 3
"iceland", score 10
Prefix "i" -> iceland, i love you, ironman.
Wait, multi-word autocomplete?
Usually, a trie is for tokens. If we want sentence autocomplete, the trie keys are the words of the sentence.
Let's stick to single word autocomplete for the simplest, most robust demonstration.
Plan:
TrieNode class.
AutocompleteSystem class containing the Trie.
- Methods:
insert(word, score), get_suggestions(prefix, k).
- Demo code.
Refining the get_suggestions:
It returns a list of strings.
If the prefix itself is a word, include it.
Let's write the code.
Here is a complete, executable Python program that implements an Autocomplete system using a Trie data structure.
It includes scoring (frequency/weight) to ensure the most relevant results appear first, and uses DFS (Depth First Search) to traverse the trie efficiently.
The Python Program
import collections
class TrieNode:
def __init__(self):
# Maps a character to a TrieNode
self.children = {}
# A dictionary mapping a full sentence/word to its score (frequency).
# We store this here to access scores immediately at the prefix node.
self.scores = collections.Counter()
# Flag to indicate if this node represents the end of a specific word
self.is_end = False
class AutocompleteSystem:
def __init__(self):
self.root = TrieNode()
def insert(self, word, score=1):
"""
Inserts a word into the trie and assigns a score to it.
Time Complexity: O(L), where L is the length of the word.
"""
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
# Update the score for this word at every step (prefix)
# This allows us to find candidates quickly later.
node.scores[word] += score
node.is_end = True
def _search_node(self, prefix):
"""
Helper to traverse to the node corresponding to the end of the prefix.
Returns None if prefix not found.
"""
node = self.root
for char in prefix:
if char not in node.children:
return None
node = node.children[char]
return node
def get_suggestions(self, prefix, top_k=3):
"""
Returns the top_k suggestions for a given prefix based on score.
Time Complexity: O(P + N log N) where P is prefix length, N is number of candidates.
"""
start_node = self._search_node(prefix)
if not start_node:
return []
# The start_node already contains a dictionary of all words
# that share this prefix and their accumulated scores.
candidates = start_node.scores
# Sort candidates:
# 1. By Score (Descending) -> -item[1]
# 2. By Alphabetical Order (Ascending) -> item[0]
sorted_candidates = sorted(candidates.items(), key=lambda item: (-item[1], item[0]))
# Return only the top_k words
return [word for word, score in sorted_candidates[:top_k]]
# ==========================================
# Example Usage / Driver Code
# ==========================================
if __name__ == "__main__":
# Initialize system
ac_system = AutocompleteSystem()
# Database of sentences/words with initial scores (frequencies)
# Higher score = higher priority.
dataset = [
("apple", 10),
("app", 5),
("application", 8),
("banana", 9),
("ball", 6),
("bat", 2),
("apply", 12),
("appetite", 1)
]
print("Building Trie...")
for word, score in dataset:
ac_system.insert(word, score)
# Test Case 1: Prefix "app"
# Expected: apply (12), apple (10), application (8)
prefix = "app"
print(f"\nInput: '{prefix}'")
print(f"Top 3 Suggestions: {ac_system.get_suggestions(prefix)}")
# Test Case 2: Prefix "b"
# Expected: banana (9), ball (6), bat (2)
prefix = "b"
print(f"\nInput: '{prefix}'")
print(f"Top 3 Suggestions: {ac_system.get_suggestions(prefix)}")
# Test Case 3: Dynamic Update
# Let's simulate a user selecting "app" multiple times, increasing its score
print("\n--- User selects 'app' 15 times ---")
ac_system.insert("app", 15) # Increment score by 15. Total becomes 20.
# Test Case 4: Prefix "app" again
# Expected: app (20), apply (12), apple (10)
prefix = "app"
print(f"\nInput: '{prefix}'")
print(f"Top 3 Suggestions: {ac_system.get_suggestions(prefix)}")
# Test Case 5: Unknown prefix
prefix = "xyz"
print(f"\nInput: '{prefix}'")
print(f"Top 3 Suggestions: {ac_system.get_suggestions(prefix)}")
How it Works
-
TrieNode Structure:
children: A standard dictionary mapping characters to subsequent nodes.
scores: This is the key to the scoring system. Every node in the trie (not just the leaf) keeps a dictionary (Counter) of all complete words that pass through it, mapped to their current scores.
- For example, if we insert "apple", the nodes for
a, p, p, l, and e will all hold a reference to "apple" and its score.
-
Insertion (insert):
- When inserting a word (e.g., "apple"), we traverse character by character.
- At every step along the path (a -> ap -> app -> ...), we update the score for "apple". This makes lookup extremely fast because we don't need to traverse the whole tree to find sub-words; the sub-words are already listed at the prefix node.
-
Scoring & Ranking (get_suggestions):
- We find the node corresponding to the input
prefix.
- We retrieve the
scores dictionary stored at that node. This dictionary contains only the words that start with that prefix.
- We sort the dictionary items. The sorting logic uses a tuple:
(-score, word).
-score: Sorts score Descending (highest first).
word: Sorts alphabetically Ascending (tie-breaker).
-
Complexity:
- Insert: O(L⋅, where is word length and is the number of times we update the score map (usually fast).