Trie (Prefix Tree)

Active
Target
Pivot
idle
Initializing...
Time Complexity
Best
O(m)O(m)
Average
O(m)O(m)
Worst
O(m)O(m)
Space Complexity
O(ALPHABET⋅n)O(ALPHABET \cdot n)
StabilityFALSE
In-placeFALSE

Explanation

What is a Trie (Prefix Tree)?

A Trie (pronounced "try") is a tree-like data structure used to efficiently store and search a set of strings. The name comes from the word "retrieval", and it is also commonly known as a "Prefix Tree".

Key Features

  • Prefix Sharing: All strings that begin with the same sequence of characters share the same path from the root.
  • Fast Lookup: Searching for a string of length mm takes O(m)O(m) time, which is independent of the number of strings in the trie.

How it Works

1. Insertion
  1. Start at the root and iterate through each character of the string.
  2. If the current character is not a child of the current node, create a new child node.
  3. Once the entire string is processed, mark the final node as the "end of a word".
2. Binary Search
  1. Follow the path corresponding to each character of the search query.
  2. If any character is missing, the word does not exist.
  3. If all characters are found and the final node is marked as "end of word", the search is successful.

Complexity

  • Search & Insert: O(m)O(m) (mm is the length of the string)
  • Space Complexity: O(ALPHABET_SIZE⋅n)O(ALPHABET\_SIZE \cdot n) (nn is the total number of characters. Space is often saved by prefix sharing).

Pseudo Code

1procedure insert(word)
2 curr = root
3 for char in word
4 if char not in curr.children
5 curr.children[char] = new Node()
6 curr = curr.children[char]
7 curr.isEndOfWord = true
8end procedure
Sponsor Ad