What is a trie (prefix tree)?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Data Structures & Algorithms development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
A trie (prefix tree or digital tree) is a tree-shaped data structure for storing strings, where each node represents a character and paths from root to nodes represent prefixes. Nodes share common prefixes — "car" and "cat" share the "ca" prefix. Operations: Insert: O(m) where m = string length — walk/create nodes for each character; Search: O(m) — traverse characters from root; Prefix search (startsWith): O(p) where p = prefix length; Delete: O(m). Space: O(ALPHABET_SIZE × n × m) worst case. Implementation: each node has a children array/map (26 children for lowercase English, or hashmap for Unicode) and a boolean isEndOfWord. Applications: (1) Autocomplete / typeahead — find all words with given prefix; (2) Spell checker; (3) IP routing (longest prefix matching); (4) Word games (Boggle, Scrabble); (5) Phone contacts search; (6) Dictionary implementation. Advantages over hash map for strings: supports prefix queries; alphabetically sorted iteration; no hash collisions. Disadvantage: higher memory usage (many nodes). Compressed trie (Patricia trie, Radix tree) reduces nodes by compressing single-child chains.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Data Structures & Algorithms answers easy to follow.