Skip to main content

Preview — Pro guide

You are seeing a portion of this guide. Sign in and upgrade to unlock the full article, quizzes, and interview answers.

DSA·Intermediate

Tries (Prefix Trees): Autocomplete, Word Search, and Wildcard Matching

Build production-ready tries for O(L) prefix operations, solve Word Search II with backtracking pruning, and implement wildcard matching. Covers the prefix-count optimization used in autocomplete systems.

35 min read 3 sections 1 interview questions
TriePrefix TreeAutocompleteWord SearchBacktrackingWildcard MatchingPrefix CountTrieNodeDictionaryString AlgorithmsIP RoutingSpell Check

How to Decide When a Trie Is the Right Data Structure

01

Check if the operation involves prefixes

Hash maps give O(1) exact lookup but O(n) prefix queries. If the problem involves 'all words starting with X', 'count words with prefix', or 'autocomplete', a trie is the right choice. For exact-match only, prefer a hash set.

02

Identify the alphabet and node structure

Lowercase English only: array of 26 is 3-5x faster. Unicode, digits, or mixed: use dict children. Always add is_end: bool to mark valid word boundaries. Add count: int only if prefix-frequency queries are required.

03

Implement insert first, then build search on top

Insert creates nodes for each character and sets is_end=True at the last character. Search reuses the same traversal but checks is_end at the end. StartsWith is search without the is_end check. Extract the shared traversal into a helper.

04

For grid word search, combine trie with backtracking

Build a trie from all target words. Run one DFS from every grid cell, simultaneously walking the trie. At each step, check if the current char exists in the trie node's children. If not, prune — no word can start with this path.

05

Prune after finding each word

After finding a word, set is_end=False and remove leaf nodes that are now empty (no children, not is_end). This prevents finding the same word multiple times and prunes future grid DFS paths that no longer lead to any word.

IMPORTANT

Premium content locked

This guide is premium content. Upgrade to Pro to unlock the full guide, quizzes, and interview Q&A.