Trie
Store words letter by letter in a tree where shared prefixes share one path; a search depends only on the word's length, not on how many words there are.
In a trie (from retrieval) each edge is a letter and each node a prefix. Words with a common prefix (like tea and ten) share a path. A node where a word ends is marked.
Read the full explanation ↓- Time:
O(word length) per insert or search - Space:
O(total letters) - Horowitz–Sahni, chapter 10
The words tea, ten, to, in, inn; te and in are shared paths. The search for ten succeeds.
def trie(words, query):children = [{}] # children[node] maps a letter to a child node; node 0 is the rootend = [False] # end[node]: some word ends hererows = [[0, "", "", ""]] # for the picture: node, prefix, child letters, word endfor word in words.split():node = 0for ch in word:if ch not in children[node]:children.append({})end.append(False)children[node][ch] = len(children) - 1rows.append([len(children) - 1, rows[node][1] + ch, "", ""])rows[node][2] = "".join(sorted(children[node]))node = children[node][ch]end[node] = Truerows[node][3] = "word"node = 0for i in range(len(query)):if query[i] not in children[node]:return Falsenode = children[node][query[i]]found = end[node]return found
Start
The table is still empty.
Local variables
Orange = changed in this step
Call stack
- trie()line 1
Explanation
The idea
In a trie (from retrieval) each edge is a letter and each node a prefix. Words with a common prefix (like tea and ten) share a path. A node where a word ends is marked.
Insert and search
- Insert: walk from the root letter by letter; where there is no edge, make a new node; mark the last node.
- Search: follow the same path; if an edge is missing or the last node is not marked, the word is not there.
Cost
Each operation is O(word length), whatever the number of words. Uses: autocomplete, spell checkers and IP routing
tables.
What to watch in the trace
- The table lists every node: its prefix, its children's letters, and whether a word ends there.