Advanced data structuresAnimated
Trie
A tree where each edge is a character.
Time
O(m) per operation
Extra space
O(total chars)
Use it for
Prefix search and autocomplete.
How it works
- A trie (prefix tree) stores words letter by letter: every node is one letter, and a path from the root spells a prefix.
- Insert a word by following its letters from the root. Where a letter has no child yet, create one. Mark the last node as "end of a word".
- Words that share a start share nodes, so "tea", "ten" and "to" all begin with the same first node.
- To search, follow the letters. If you fall off the trie the word is absent. If you reach the end, it is a word if the node is marked, and otherwise only a prefix. O(length of the word).
Watch it run
Loading animation…