Designing recursive fuzzy trie search
Outlined a recursive trie traversal that tracks Levenshtein edit distance (insertions, deletions, substitutions) to find fuzzy autocomplete matches within a max threshold, including a sketch of both dynamic programming and simpler recursion approaches. Next is to implement and refine this recursive search respecting pruning and correctness.
What you put into your index is the same as for a normal autocomplete: a trie where each node has a map of children and a flag that marks the end of a word. The only difference is how you walk it at query time.
A Levenshtein edit consists of three primitive moves:
- consume one character from the input and one from the trie (match or substitution),
- consume one character from the input without moving in the trie (deletion from the input),
- move to a child in the trie without consuming input (insertion into the input).
If you carry along “how many edits have I spent so far?”, you can explore those branches recursively and prune anything that would exceed your maximum distance.
One way of doing it in Python is:
class Node:
__slots__ = ('children', 'is_word')
def __init__(self):
self.children = {} # char -> Node
self.is_word = False
class Autocomplete:
def __init__(self):
self.root = Node()
def insert(self, word: str) -> None:
n = self.root
for ch in word:
n = n.children.setdefault(ch, Node())
n.is_word = True
def fuzzy(self, query: str, max_dist: int = 2):
results = []
self._dfs(self.root, query, 0, 0, '', results, max_dist)
return results
def _dfs(self, node: Node, query: str, i: int, dist: int,
prefix: str, out: list, max_dist: int) -> None:
# prune if we've already spent too many edits
if dist > max_dist:
return
# if we've consumed the entire query, any trailing trie path
# costs one edit per character
if i == len(query):
if node.is_word:
out.append(prefix)
for ch, child in node.children.items():
self._dfs(child, query, i, dist+1, prefix+ch, out, max_dist)
return
# deletion from the input: skip query[i]
self._dfs(node, query, i+1, dist+1, prefix, out, max_dist)
# match or substitution
for ch, child in node.children.items():
if ch == query[i]:
# characters match, no cost
self._dfs(child, query, i+1, dist, prefix+ch, out, max_dist)
else:
# substitution
self._dfs(child, query, i+1, dist+1, prefix+ch, out, max_dist)
# insertion into the input (i.e. extra character in the trie)
self._dfs(child, query, i, dist+1, prefix+ch, out, max_dist)
Calling fuzzy("aple", max_dist=1) on a trie that contains "apple" will return ["apple"] because one insertion is enough to align the input and the stored word.
For better performance on longer queries you can also use the standard “row‑by‑row” Levenshtein algorithm while traversing the trie. You carry a DP row for the current node and compute the next row for each child:
def fuzzy(self, query, max_dist):
results = []
initial_row = list(range(len(query) + 1))
def recurse(node, char, prev_row, word):
# Compute the current row
curr_row = [prev_row[0] + 1]
for i, qc in enumerate(query, 1):
insert_cost = curr_row[i-1] + 1
delete_cost = prev_row[i] + 1
replace_cost = prev_row[i-1] + (0 if qc == char else 1)
curr_row.append(min(insert_cost, delete_cost, replace_cost))
# Check for match
if node.is_word and curr_row[-1] <= max_dist:
results.append(word)
# Prune
if min(curr_row) <= max_dist:
for c, child in node.children.items():
recurse(child, c, curr_row, word + c)
for c, child in self.root.children.items():
recurse(child, c, initial_row, c)
return results
Both versions keep the traversal within a maximum edit distance and will suggest "apple" when the user types "aple".