Back to Dashboard
Trie (Prefix Tree)
An efficient search tree where keys are usually strings, allowing for fast prefix-based lookups.
Active
Target
Pivot
idle
Initializing...
Time Complexity
Best
Average
Worst
Space Complexity
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 takes time, which is independent of the number of strings in the trie.
How it Works
1. Insertion
- Start at the root and iterate through each character of the string.
- If the current character is not a child of the current node, create a new child node.
- Once the entire string is processed, mark the final node as the "end of a word".
2. Binary Search
- Follow the path corresponding to each character of the search query.
- If any character is missing, the word does not exist.
- If all characters are found and the final node is marked as "end of word", the search is successful.
Complexity
- Search & Insert: ( is the length of the string)
- Space Complexity: ( is the total number of characters. Space is often saved by prefix sharing).
Pseudo Code
1procedure insert(word)2 curr = root3 for char in word4 if char not in curr.children5 curr.children[char] = new Node()6 curr = curr.children[char]7 curr.isEndOfWord = true8end procedure
Sponsor Ad