Design a Trie-based autocomplete system with fuzzy matching. If the user types aple, return apple. Implement recursive search allowing 1 or 2 insertions, deletions, or substitutions using Levenshtein distance while traversing the tree.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a comprehensive request for implementing a Trie-based autocomplete system with fuzzy matching capabilities. Let me break down what needs to be implemented:
Trie Data Structure: A tree-like structure for efficient string storage and retrieval
Fuzzy Matching: Using Levenshtein distance (edit distance) to allow 1-2 insertions, deletions, or substitutions
Recursive Search: Traversing the trie while calculating edit distance
Autocomplete: Returning suggestions based on prefix and fuzzy matching
Here's my approach:
Build a Trie node structure
Implement Insert operation
Implement Search/Autocomplete with fuzzy matching using recursive DFS with Levenshtein distance
The fuzzy search will consider:
Character match (no edit)
Insertion (skip character in query)
Deletion (skip character in trie path)
Substitution (replace character)
Use memoization to optimize the recursive search
Return results sorted by relevance (exact matches first, then by edit distance, then alphabetically)
Let me write comprehensive code with:
Trie implementation
Fuzzy search with edit distance
Autocomplete functionality
Test cases
Explanations
python
class TrieNode:
"""Node in the Trie structure"""
def __init__(self):
self.children = {}
self.is_word = False
self.word = "" # Store the actual word for easy retrieval
class TrieAutocomplete:
"""Trie-based autocomplete system with fuzzy matching"""
def __init__(self, max_edits=2):
"""
Initialize the autocomplete system
Args:
max_edits: Maximum number of edit operations allowed (1 or 2)
"""
self.root = TrieNode()
self.max_edits = max_edits
def insert(self, word):
"""
Insert a word into the trie
Args:
word: Word to insert
"""
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_word = True
node.word = word
def levenshtein_distance(self, s1, s2):
"""
Calculate the Levenshtein distance between two strings using dynamic programming
"""
m, n = len(s1), len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i-1] == s2[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
return dp[m][n]
The Levenshtein distance calculation uses a space-optimized approach that tracks insertions, deletions, and substitutions between the two strings. The fuzzy search traverses the trie recursively, building candidate words and calculating their edit distances against the query, then returns the best matches sorted by distance and alphabetically. # Option 2: Substitution - replace current char
if edits_used < self.max_edits:
for child_char in node.children:
if child_char != current_char:
self._fuzzy_search_helper(
node.children[child_char],
query,
query_idx + 1,
edits_used + 1,
current_word + child_char,
results
)
code
# Option 3: Insertion - skip a character in dictionary
if edits_used < self.max_edits:
for child_char in node.children:
self._fuzzy_search_helper(
node.children[child_char],
query,
query_idx, # Don't advance query
edits_used + 1,
current_word + child_char,
results
)
When we have edits remaining, I can try substituting the current character with any child node that doesn't match, incrementing the edit count. I also explore insertions by traversing child nodes without advancing through the query, treating extra dictionary characters as insertions into the search term.
For deletions, I skip ahead in the query while staying at the current node, and then I need to collect all valid words from any subtree once I've exhausted the query string. The autocomplete method first attempts exact prefix matching by traversing the trie, then falls back to fuzzy search if the prefix doesn't exist, or supplements prefix results with fuzzy matches if needed.
When collecting prefix words, each match gets an edit distance of 0 since they're exact prefix matches. Results are sorted by edit distance first, then alphabetically, before returning the top matches. An advanced version extends this with word frequency tracking for better ranking.
The enhanced autocomplete accepts a frequency parameter during insertion to track word popularity. Its fuzzy search implementation calculates a composite score that favors lower edit distances and higher frequency words, providing more relevant results based on both similarity and usage patterns. _edits=2)
code
# Add words with frequencies (simulating popularity)
words = {
"apple": 100,
"application": 90,
"apply": 80,
"appreciate": 70,
"apricot": 60,
"april": 50,
"apt": 40,
"app": 95,
"apex": 30,
"apartment": 85,
"apparatus": 25,
}
for word, freq in words.items():
autocomplete.insert(word, freq)
print("\n1. Testing fuzzy search for 'aple' (missing 'p'):")
print("-" * 60)
results = autocomplete.fuzzy_search("aple", max_results=5)
for i
print("\n2. Testing fuzzy search for 'aplcation' (typo):")
print("-" * 60)
results = autocomplete.fuzzy_search("aplcation", max_results=5)
for i, (word, edit_dist, score) in enumerate(results, 1):
print(f" {i}. {word:15} | Edit Distance: {edit_dist} | Score: {score:.2f}")
print("\n3. Testing fuzzy search for 'appl' (incomplete):")
print("-" * 60)
results = autocomplete.fuzzy_search("appl", max_results=5)
for i, (word, edit_dist, score) in enumerate(results, 1):
print(f" {i}. {word:15} | Edit Distance: {edit_dist} | Score: {score:.2f}")
print("\n4. Testing fuzzy search for 'apr' (prefix):")
print("-" * 60)
results = autocomplete.fuzzy_search("apr", max_results=5)
for i, (word, edit_dist, score) in enumerate(results, 1):
print(f" {i}. {word:15} | Edit Distance: {edit_dist} | Score: {score:.2f}")
print("\n5. Testing autocomplete for 'apl' (typo in prefix):")
print("-" * 60)
results = autocomplete.autocomplete("apl", max_results=5)
for i, result in enumerate(results, 1):
if len(result) == 3:
word, edit_dist, score = result
print(f" {i}. {word:15} | Edit Distance: {edit_dist} | Score: {score:.2f}")
else:
word, edit_dist = result
print(f" {i}. {word:15} | Edit Distance: {edit_dist}")
print("\n6. Testing with max_edits=1:")
print("-" * 60)
autocomplete1 = AdvancedTrieAutocomplete(max_edits=1)
for word, freq in words.items():
autocomplete1.insert(word, freq)
results =
I'm completing the test cases by adding prefix-based autocomplete checks alongside the fuzzy search tests, then moving into testing with a stricter edit distance constraint.
code
autocomplete1.fuzzy_search("aple", max_results=5)
for i, (word, edit_dist, score) in enumerate(results, 1):
print(f" {i}. {word:15} | Edit Distance: {edit_dist} | Score: {score:.2f}")
print("\n7. Testing fuzzy search for 'apricate' (2 errors):")
print("-" * 60)
results = autocomplete.fuzzy_search("apricate", max_results=5)
for i, (word, edit_dist, score) in enumerate(results, 1):
print(f" {i}. {word:15} | Edit Distance: {edit_dist} | Score: {score:.2f}")
The fuzzy search implementation needs refinement. Rather than building words character-by-character during trie traversal, a cleaner approach would traverse the entire trie, compute Levenshtein distance for each word, filter by the max_edits threshold, and sort by distance. However, the requirement specifies recursive traversal with edit distance calculations, so the implementation should balance efficiency with the constraint of traversing the tree structure while computing distances dynamically.
The optimal strategy involves DFS through the trie while maintaining the current character sequence and using dynamic programming to calculate edit distance incrementally. This allows pruning branches that exceed the edit threshold, leveraging the trie structure to reduce the search space.
python
class TrieNode:
"""Node in the Trie structure"""
def __init__(self):
self.children = {}
self.is_word = False
self.word = ""
class TrieAutocompleteFuzzy:
"""Trie-based autocomplete with fuzzy matching using Levenshtein distance"""
def __init__(self, max_edits=2):
self.root = TrieNode()
self.max_edits = max_edits
def insert(self, word):
"""Insert a word into the trie"""
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_word = True
node.word = word
def fuzzy_search(self, query, max_results=10):
"""Search for words matching the query with fuzzy matching"""
results = []
initial_row = list(range(len(query) + 1))
self._fuzzy_search_recursive(
node=self.root,
query=query,
previous_row=initial_row,
trie_path="",
results=results
)
seen = set()
unique_results = []
for word, dist in results:
if word not in seen:
seen.add(word)
unique_results.append((word, dist))
unique_results.sort(key=lambda x: (x[1], x[0]))
return unique_results[:max_results]
def _fuzzy_search_recursive(self, node, query, previous_row, trie_path, results):
"""Traverse trie recursively, computing edit distance incrementally using Wagner-Fischer"""
current_row = [previous_row[0] + 1]
for col in range(1, len(query) + 1):
insert_cost = current_row[col - 1] + 1
delete_cost = previous_row[col] + 1
replace_cost = previous_row[col - 1] + (0 if trie_path[-1] == query[col - 1] else 1)
current_row.append(min(insert_cost, delete_cost, replace_cost))
if current_row[-1] <= self.max_edits and node.is_word:
results.append((node.word, current_row[-1]))
if min(current_row) <= self.max_edits:
for char, child_node in node.children.items():
self._fuzzy_search_recursive(
child_node,
query,
current_row,
trie_path + char,
results
)
The implementation uses incremental DP calculation as we traverse down the trie, collecting words within the edit distance threshold and pruning branches where the minimum distance exceeds the limit. in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j], # deletion
dp[i][j - 1], # insertion
dp[i - 1][j - 1]) # substitution
code
return dp[m][n]
def fuzzy_search(self, query, max_results=10):
"""
Perform fuzzy search with recursive trie traversal
Allows up to max_edits (insertions, deletions, substitutions)
"""
results = []
def dfs(node, current_path, edits_remaining):
# Calculate edit distance from query to current path
distance = self._levenshtein_distance(query, current_path)
# Prune if distance exceeds threshold
if distance > self.max_edits:
return
# If this is a word node and within edit distance, add to results
if node.is_word and distance <= self.max_edits:
results.append((node.word, distance))
# Continue DFS through children
for char, child_node in node.children.items():
dfs(child_node, current_path + char, edits_remaining)
dfs(self.root, "", self.max_edits)
# Sort by edit distance and return top results
results.sort(key=lambda x: x[1])
return [word for word, _ in results[:max_results]]
I'm realizing the recursive DFS approach with edit distance calculation at each node will work well. The key is computing Levenshtein distance between the query and the current trie path, then pruning branches that exceed the threshold. When reaching word-marked nodes within the edit distance limit, I collect them and sort by distance to return the best matches. True
node.word = word
code
def fuzzy_search(self, query, max_results=10):
"""
Fuzzy search allowing up to max_edits edit operations.
Uses recursive DFS with incremental Levenshtein distance computation.
"""
results = []
# Initialize: each query character requires 1 insertion from empty prefix
initial_row = list(range(len(query) + 1))
self._fuzzy_search_recursive(
node=self.root,
query=query,
previous_row=initial_row,
results=results
)
# Remove dups and sort
seen = {}
for word, dist in results:
if word not in seen or dist < seen[word]:
seen[word] = dist
I'm realizing the earlier approach of comparing prefixes directly won't work—I need to track edit distance incrementally as I traverse. By maintaining the DP table row from Wagner-Fischer, I can prune branches where the minimum distance already exceeds the threshold. This way, I only collect words that could plausibly match within the edit limit, then deduplicate and sort the final results. _search_recursive(
node=child_node,
query=query,
previous_row=current_row,
results=results,
char_from_parent=char
)
The autocomplete method combines prefix matching as the primary strategy, falling back to fuzzy matching when an exact prefix isn't found. It first traverses the trie to locate the prefix node, then collects all words beneath that node with zero edit distance. If the prefix doesn't exist in the trie, it triggers a fuzzy search from the root using the full query string.
When merging results, exact prefix matches take priority over fuzzy matches, and duplicates are filtered out before sorting by edit distance and alphabetically. The helper method recursively gathers all valid words from a given subtree, appending each word found along with its associated edit distance to the results list.
Trie-Based Autocomplete with Fuzzy Matching
Here's a comprehensive implementation with recursive search and Levenshtein distance: