Day 58
Day 58: Tries
58/60 Days
Day 58: Tries #
Welcome to Day 58 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore Tries, an efficient tree-like data structure used for storing and retrieving strings.
What is a Trie? #
A Trie, also called a prefix tree, is a tree-like data structure used to store a dynamic set or associative array where the keys are usually strings. Unlike a binary search tree, no node in the tree stores the key associated with that node; instead, its position in the tree defines the key with which it is associated.
Properties of Tries #
- The root represents an empty string.
- Each node (except the root) stores a character and has up to 26 children (for English alphabet).
- Each path from the root to a node represents a prefix of one or more strings.
- Nodes can store additional information, like whether they represent the end of a word.
Implementation #
Here’s a Python implementation of a Trie:
1class TrieNode:
2 def __init__(self):
3 self.children = {}
4 self.is_end_of_word = False
5
6class Trie:
7 def __init__(self):
8 self.root = TrieNode()
9
10 def insert(self, word):
11 node = self.root
12 …
Continue Reading
Sign up or log in to access the full lesson and all 60 days of algorithm content.