Intro

Trie is a tree-like data structure for storing sequences of tokens (characters, permutations of digits or shapes, etc.) where:

Bitwise Trie uses individual bits from fixed-length binary data, such as integers or memory addresses, as keys

Usage

Comparison

Advantages

Disadvantages

Problems

Corner Cases

Implementation

Trie

insert(word)

remove(word)

isPrefix() - returns true if any word in the Trie begins with the given prefix

isWord(word) - returns true if the given word is present in the Trie

getWordWithPrefix(prefix) - return any word in the Trie that begins with the given prefix

getWordsWithPrefix(prefix) - return all words in the Trie that begin with the given prefix

getTotalWordsWithPrefix(prefix) - return the number of words in the Trie that begin with given prefix

getTotalWords() - return the number of words in the Trie

Time Complexity
Operations Worst case
create() O(l*n)
insert(word) O(m*n)
remove(word) O(m*n)
isPrefix()
isWord(word) O(m*n)
getWordWithPrefix(prefix)
getWordsWithPrefix(prefix)
getTotalWordsWithPrefix(prefix)
getTotalWords()
Space Complexity
Implementation Worst case
Trie O(n)

l is the length of the longest string in the Trie

m is the length of the average string used in the operation

n is the number of words in the Trie

alphabet_size

Algorithms

Patterns

Code


Resources

Trying to Understand Tries

Insert

void insert(String key)

Function to insert a key in the trie.

Inserts the string key into the trie.

Every character of the input key is inserted as an individual Trie node.

Note that the children is an array of pointers (or references) to next level trie nodes. The key character acts as an index to the array children.

If the input key is new or an extension of the existing key, we need to construct non-existing nodes of the key, and mark the end of the word for the last node.

If the input key is a prefix of the existing key in Trie, we simply mark the last node of the key as the end of a word.

The key length determines Trie depth.

Remove

void remove(String key)

Function to delete a key in the trie.

During delete operation we delete the key in bottom-up manner using recursion. The following are possible conditions when deleting key from trie:

  1. Key may not be there in trie. Delete operation should not modify trie.
  2. Key present as unique key (no part of key contains another key (prefix), nor the key itself is prefix of another key in trie). Delete all the nodes.