Trie | Data structure implementation in Typescript
Sandro Maglione
Get in touch with meWeb development
5 June 2023
β’3 min read
Sandro Maglione
Web development
In my projects I work a lot with list of words. If you ever have to deal with words and texts, you will eventually discover (and implement) a Trie data structure.
This is what happened to me. I ended up implementing a Trie
in various languages and with different strategies.
Finally, I settled on one implementation that is efficient and complete (complete enough for my purposes).
Here it is π
What is a Trie
?
A Trie is a data structure used to store a list of words. Using a Trie makes searching for a word efficient (O(dm)
, where d
is the length of the string you are searching, and m
is the alphabet size).
When to use a Trie
Following a simple usecase example.
You have a list of words and a long text, and you want to search all the occurrences of each word in the text.
The naive / brute-force approach consists splitting the text in words and, for each word, search in the list. This gets slow pretty fast π
In this case a Trie
is ideal, since it stores words more efficiently and it makes searching much faster ποΈ
How to use Trie
You usually start from a list of words.
You can build a Trie
from the list using the static constructor buildTrie
:
That's basically it! ππΌββοΈ
Now the Trie
allows to search for any word (using searchTrie
) and add any word (using addWord
):
Note: This
Trie
implementation is mutable, you are allowed to modify theTrie
(children
,addWord
,addChar
) βοΈ