Browse curriculum

Trie

The Trie Pattern

A tree where each edge is a character, so words sharing a prefix share a path. Lookup cost depends on the length of the word rather than the number of words stored.

3

Interactive problems

1

Free to open

Recognise

How do you recognise a trie problem?

The problem involves prefixes — autocomplete, prefix search, word dictionaries — or repeatedly checks membership of many strings. Grid word-search problems use a trie to prune impossible branches early.

Complexity

What is the time complexity of the trie pattern?

O(L) per insert or search, where L is word length, independent of how many words are stored. Space is O(total characters) in the worst case.

Problems

Trie practice problems

Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.

Complexity

Trie problems by difficulty and complexity

The difficulty, running time and extra space of every trie solution on this page, as each lesson derives them.

LessonDifficultyBestAverageWorstSpace
Introduction to Tries (Prefix Trees)MediumΩ(1)Θ(L)O(L)O(N·L)
Implement Trie (Prefix Tree)MediumΩ(1)Θ(L)O(L)O(N·L)
Prefix MatchingMediumΩ(1)Θ(L)O(L)O(1)
Curriculum

The underlying technique is covered from first principles in the trie lesson in the DSA visualizer curriculum. Trie is one of the 17 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern