Browse curriculum

Trie

Trie Interview Questions: 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. Below are the trie interview questions from LeetCode, each with a step-by-step visual solution.

6

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 interview questions: 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)
Design Add and Search WordsMediumΩ(1)Θ(L)O(N)O(total letters)
Word Search IIHardΩ(m · n)Θ(m · n · 3^L)O(m · n · 3^L)O(total letters)
Maximum XOR of Two Numbers in an ArrayMediumΩ(n · B)Θ(n · B)O(n · B)O(n · B)
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 18 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern