Skip to content
IT glossary
AlgorithmsUpdated December 3, 2026

Trie

Префиксное дерево

A data structure that stores strings in a tree, sharing branches for strings with the same beginning. It can tell you whether an exact string is present and help you find all strings that start with a given prefix.

Also known as: бор, trie

What a trie stores

Suppose a search box needs to suggest car, card, and care when someone types ca. A trie, or prefix tree, stores the path for ca once. Instead of checking every word in the dictionary, the search box can follow that path and look for matches below it.

How the tree works

The root represents the empty prefix. In a standard trie, each edge represents one character, so reading the edges from the root to a node gives you a prefix. Each node stores its outgoing edges and a flag that says whether a complete key ends there. A node can mark the end of a key and still have children: car is a complete key even though card continues from it.

root
└─ c
   └─ a
      └─ r *
         ├─ d *
         └─ e *

Here * marks the end of a stored key. startsWith("ca") succeeds because both edges exist; search("ca") fails because the a node is not marked. Inserting cart reuses the path for car, adds an edge for t, and marks the new node. To list completions for ca, find its node and traverse the subtree, emitting a key at each marked node.

Time and memory trade-offs

With constant-time access to a child, inserting a string or checking an exact key or prefix of length m takes O(m) time. If children are stored in a hash map, that bound is expected rather than guaranteed. Listing completions adds the cost of visiting the subtree and building the returned strings. Even a short prefix can have thousands of matches.

A standard trie has one node per distinct nonempty prefix, plus the root. For a small alphabet, an array at each node makes child lookup simple, but unused slots still take up space. A map stores only the edges that exist, at the cost of map overhead. A trie shares common prefixes, but that does not guarantee it will use less memory than a hash set or a sorted array of strings.

Choosing and implementing a trie

Tries are useful for autocomplete and dictionaries that receive frequent prefix queries. A plain trie finds candidates; it does not know which ones should rank first. If you only need exact membership tests, a hash set is usually simpler. For a static dictionary, a sorted array is another option: binary search can find the start of the contiguous range of matching keys.

A common interview exercise is to implement insert, search, and startsWith. Test with both car and card to show that a key can end at an internal node. If deletion is required, clear the end flag first, then prune only nodes that no longer have children and do not end another key.