Question presented to candidate: "What is a trie, and when would you use one instead of a hash set or a sorted list? Sketch the node structure and the basic operations in Python."
What a strong answer should cover:
- A trie stores strings one character per edge; words with a common prefix share a path, and an end-of-word flag marks complete words.
insert,searchandstartsWitheach cost O(L) in the word length, independent of how many words are stored, andsearchdiffers fromstartsWithonly by the end-flag check.- When it wins: prefix queries (autocomplete, prefix counts), wildcard search, longest-prefix match; when it loses: exact-match-only lookups, where a hash set is smaller and simpler.
- The memory trade-off: one node per distinct prefix, and per node either a fixed array (fast, wasteful) or a map (compact, slower).
- Python details: children as a
dict(any character),__slots__to shrink nodes,dict.getfor the walk, andsorted()because dicts keep insertion order, not alphabetical order.
Code / implementation expected: Optional β a Trie class with insert, search and startsWith in Python is a common follow-up.