Sub topic 12
Longest-Prefix Matching
This chapter assumes you can write the insert and search methods from the earlier chapters and that you know the end-of-word marker. It builds on both.
The problem
Exact search asks whether a whole key is stored. Longest-prefix matching asks a different question: which stored key is the longest one that the beginning of the input starts with?
A router faces this problem. A routing table might hold the prefixes 1, 10 and 1011, each with a next hop. An incoming address 101101 matches all three prefixes, so the router picks the longest one, 1011. Any key that is a prefix of the input is a candidate. You want the deepest candidate.
The idea
Walk the input from the root, one character at a time. Whenever the current node has is_end set, remember it as the best match so far. Stop when the next child is missing or the input runs out. The remembered match is the answer.
The point to notice is that the last node you reach is not necessarily the answer. For the input 1001, the walk reaches 10 and then fails at 100. The answer is 10, which you recorded while passing through.
Implementation
This version stores a value in each end node, as in the previous chapter on node metadata. It returns the matched key and its value, or None if no stored key is a prefix of the input.
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
self.value = None
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word, value=None):
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.is_end = True
node.value = value
def longest_prefix(self, text):
node = self.root
best = None # (length, value) of the deepest end node seen
if node.is_end:
best = (0, node.value) # the empty key matches everything
for i, ch in enumerate(text):
node = node.children.get(ch)
if node is None:
break
if node.is_end:
best = (i + 1, node.value)
if best is None:
return None
length, value = best
return text[:length], value
t = Trie()
t.insert("1", "C")
t.insert("10", "A")
t.insert("1011", "B")
print(t.longest_prefix("101101")) # ('1011', 'B')
print(t.longest_prefix("1001")) # ('10', 'A')
print(t.longest_prefix("0111")) # NoneTracing 1001: the walk passes 1 (best is C), then 10 (best becomes A), then finds no child 0 under 10, so it breaks. The result is 10.
Cost
The loop visits at most one node per character of the input, so the time is O(L), where L is the input length. It does not depend on how many keys are stored. The only extra state is the single best pair, so the extra space is O(1).
Compare this with a hash set. To find the longest stored prefix of a string with a hash set, you would test each prefix from longest to shortest. Each test hashes up to L characters, so the total is O(L²). A trie reads each character once.
Common errors
- Returning the last node reached. The last node may not be an end node. Always track the deepest end node separately.
- Using
starts_withlogic. A prefix check only asks whether the path exists. Here you needis_endat each step. - Forgetting the empty key. If an empty string is stored, the root is a valid match. The check before the loop handles it.
- Using
valueto detect a match. A stored value ofNonelooks the same as "no value". Useis_end, as above.
Exercise
Using the trie above, what does longestprefix("10") return, and what does longestprefix("") return? Explain each result.
Show answer
longestprefix("10") returns ('10', 'A'). The walk passes the end node 1, then reaches the end node 10 as the input runs out, so the deepest end node is 10. longestprefix("") returns None. The loop never runs, and the root is not an end node because no empty key was inserted.